Revision 305

View differences:

tags/org.gvsig.postgresql-2.0.65/pom.xml
1
<?xml version="1.0" encoding="UTF-8"?>
2

  
3
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4

  
5
  <modelVersion>4.0.0</modelVersion>
6
  <artifactId>org.gvsig.postgresql</artifactId>
7
  <version>2.0.65</version>
8
  <packaging>pom</packaging>
9
  <name>${project.artifactId}</name>
10
  <description>PostgreSQL support fort DAL and gvSIG</description>
11
  <parent>
12
      <groupId>org.gvsig</groupId>
13
      <artifactId>org.gvsig.desktop</artifactId>
14
      <version>2.0.164</version>
15
  </parent>
16

  
17
  <url>https://devel.gvsig.org/redmine/projects/gvsig-postgresql</url>
18
  <scm>
19
      <connection>scm:svn:https://devel.gvsig.org/svn/gvsig-postgresql/tags/org.gvsig.postgresql-2.0.65</connection>
20
      <developerConnection>scm:svn:https://devel.gvsig.org/svn/gvsig-postgresql/tags/org.gvsig.postgresql-2.0.65</developerConnection>
21
      <url>https://devel.gvsig.org/redmine/projects/gvsig-postgresql/repository/show/tags/org.gvsig.postgresql-2.0.65</url>
22
  </scm>
23

  
24
    <repositories>
25
        <repository>
26
            <id>gvsig-public-http-repository</id>
27
            <name>gvSIG maven public HTTP repository</name>
28
            <url>http://devel.gvsig.org/m2repo/j2se</url>
29
            <releases>
30
                <enabled>true</enabled>
31
                <updatePolicy>daily</updatePolicy>
32
                <checksumPolicy>warn</checksumPolicy>
33
            </releases>
34
            <snapshots>
35
                <enabled>true</enabled>
36
                <updatePolicy>daily</updatePolicy>
37
                <checksumPolicy>warn</checksumPolicy>
38
            </snapshots>
39
        </repository>
40
    </repositories>
41
  
42
  
43
	<build>
44
		<plugins>
45
			<plugin>
46
				<groupId>org.apache.maven.plugins</groupId>
47
				<artifactId>maven-release-plugin</artifactId>
48
				<configuration>
49
					<tagBase>https://devel.gvsig.org/svn/gvsig-postgresql/tags/</tagBase>
50
					<goals>deploy</goals>
51
				</configuration>
52
			</plugin>
53
		</plugins>
54
	</build>
55

  
56

  
57
  <dependencyManagement>
58
      <dependencies>
59
          <dependency>
60
            <groupId>org.gvsig</groupId>
61
            <artifactId>org.gvsig.postgresql.provider</artifactId>
62
            <version>2.0.65</version>
63
          </dependency>
64
          <dependency>
65
            <groupId>org.gvsig</groupId>
66
            <artifactId>org.gvsig.postgresql.app.mainplugin</artifactId>
67
            <version>2.0.65</version>
68
          </dependency>
69
      </dependencies>
70
  </dependencyManagement>
71

  
72
  <dependencies>
73
        <dependency>
74
            <groupId>org.slf4j</groupId>
75
            <artifactId>slf4j-api</artifactId>
76
            <scope>compile</scope>
77
        </dependency>
78
  </dependencies>
79

  
80
  
81
  <modules>
82
    <module>org.gvsig.postgresql.app</module>
83
    <module>org.gvsig.postgresql.provider</module>
84
  </modules>
85

  
86

  
87
</project>
tags/org.gvsig.postgresql-2.0.65/org.gvsig.postgresql.provider/pom.xml
1
<?xml version="1.0" encoding="UTF-8"?>
2

  
3
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4

  
5
  <modelVersion>4.0.0</modelVersion>
6
  <artifactId>org.gvsig.postgresql.provider</artifactId>
7
  <packaging>jar</packaging>
8
  <name>${project.artifactId}</name>
9
  <description>DAL provider for PostgeSQL files</description>
10
  <parent>
11
      <groupId>org.gvsig</groupId>
12
      <artifactId>org.gvsig.postgresql</artifactId>
13
      <version>2.0.65</version>
14
  </parent>
15

  
16
  <dependencies>
17
    <dependency>
18
        <groupId>com.googlecode.log4jdbc</groupId>
19
        <artifactId>log4jdbc</artifactId>
20
        <scope>compile</scope>
21
    </dependency>
22
    <dependency>
23
        <groupId>org.gvsig</groupId>
24
        <artifactId>org.gvsig.tools.lib</artifactId>
25
        <scope>compile</scope>
26
    </dependency>
27
    <dependency>
28
        <groupId>org.gvsig</groupId>
29
        <artifactId>org.gvsig.projection.api</artifactId>
30
        <scope>compile</scope>
31
    </dependency>
32
    <dependency>
33
        <groupId>org.gvsig</groupId>
34
        <artifactId>org.gvsig.fmap.dal.api</artifactId>
35
        <scope>compile</scope>
36
    </dependency>
37
    
38
    <dependency>
39
        <groupId>org.gvsig</groupId>
40
        <artifactId>org.gvsig.fmap.dal.db.jdbc</artifactId>
41
        <scope>compile</scope>
42
    </dependency>
43

  
44
    <dependency>
45
        <groupId>org.gvsig</groupId>
46
        <artifactId>org.gvsig.fmap.dal.db.lib</artifactId>
47
        <scope>compile</scope>
48
    </dependency>
49
    
50
    <dependency>
51
        <groupId>org.gvsig</groupId>
52
        <artifactId>org.gvsig.fmap.dal.spi</artifactId>
53
        <scope>compile</scope>
54
    </dependency>
55
    <dependency>
56
        <groupId>org.gvsig</groupId>
57
        <artifactId>org.gvsig.metadata.lib.basic.api</artifactId>
58
        <scope>compile</scope>
59
    </dependency>
60
    <dependency>
61
        <groupId>org.gvsig</groupId>
62
        <artifactId>org.gvsig.fmap.geometry.api</artifactId>
63
        <scope>compile</scope>
64
    </dependency>
65
    <!--
66
    <dependency>
67
        <groupId>org.gvsig</groupId>
68
        <artifactId>org.gvsig.fmap.geometry.operation</artifactId>
69
        <scope>compile</scope>
70
    </dependency>
71
    -->
72
    <dependency>
73
        <groupId>org.gvsig</groupId>
74
        <artifactId>org.gvsig.timesupport.lib.api</artifactId>
75
        <scope>compile</scope>
76
    </dependency>  
77
    <dependency>
78
      <groupId>org.gvsig</groupId>
79
      <artifactId>org.gvsig.utils</artifactId>
80
      <scope>compile</scope>
81
    </dependency>
82
    <dependency>
83
      <groupId>postgresql</groupId>
84
      <artifactId>postgresql</artifactId>
85
      <scope>compile</scope>
86
    </dependency>
87
    <dependency>
88
      <groupId>commons-dbcp</groupId>
89
      <artifactId>commons-dbcp</artifactId>
90
      <scope>compile</scope>
91
    </dependency>
92
    <dependency>
93
      <groupId>commons-collections</groupId>
94
      <artifactId>commons-collections</artifactId>
95
      <scope>compile</scope>
96
    </dependency>
97

  
98

  
99
    <!-- TESTS -->
100
    <dependency>
101
      <groupId>org.gvsig</groupId>
102
      <artifactId>org.gvsig.tools.lib</artifactId>
103
      <type>test-jar</type>
104
      <scope>test</scope>
105
    </dependency>
106
    <dependency>
107
      <groupId>org.gvsig</groupId>
108
      <artifactId>org.gvsig.compat.se</artifactId>
109
      <scope>test</scope>
110
    </dependency>
111
    <dependency>
112
      <groupId>org.gvsig</groupId>
113
      <artifactId>org.gvsig.fmap.dal.impl</artifactId>
114
      <type>test-jar</type>
115
      <scope>test</scope>
116
    </dependency>
117
    
118
    <!--
119
    <dependency>
120
      <groupId>org.gvsig</groupId>
121
      <artifactId>org.gvsig.fmap.dal.index.spatial.jts</artifactId>
122
      <scope>test</scope>
123
    </dependency>
124
    
125
    <dependency>
126
      <groupId>org.gvsig</groupId>
127
      <artifactId>org.gvsig.fmap.geometry.generalpath</artifactId>
128
      <scope>test</scope>
129
    </dependency>
130
    -->
131
    <dependency>
132
      <groupId>org.gvsig</groupId>
133
      <artifactId>org.gvsig.projection.cresques.impl</artifactId>
134
      <scope>test</scope>
135
    </dependency>
136
    <dependency>
137
      <groupId>org.gvsig</groupId>
138
      <artifactId>org.gvsig.timesupport.lib.impl</artifactId>
139
      <scope>test</scope>
140
    </dependency>   
141

  
142

  
143
  </dependencies>
144

  
145
</project>
tags/org.gvsig.postgresql-2.0.65/org.gvsig.postgresql.provider/src/main/resources/META-INF/services/org.gvsig.tools.library.Library
1
org.gvsig.fmap.dal.store.postgresql.PostgreSQLLibrary
tags/org.gvsig.postgresql-2.0.65/org.gvsig.postgresql.provider/src/main/resources/org/gvsig/fmap/dal/store/postgresql/PostgreSQLMetadata.xml
1
<?xml version="1.0"?>
2
<definitions>
3
  <version>1.0.0</version>
4
  <classes>
5
    <class name="PostgreSQL" namespace="Metadata">
6
      <extends>
7
      	<class name="JDBC" namespace="Metadata"/>
8
      </extends>
9
      <description>Metadata of a PostgreSQL store</description>
10
      <fields>
11
      </fields>
12
    </class>
13

  
14
  </classes>
15
</definitions>  
tags/org.gvsig.postgresql-2.0.65/org.gvsig.postgresql.provider/src/main/resources/org/gvsig/fmap/dal/store/postgresql/PostgreSQLParameters.xml
1
<?xml version="1.0"?>
2
<definitions>
3
  <version>1.0.0</version>
4
  <classes>
5
    <class name="PostgreSQLResourceParameters">
6
      <extends>
7
        <class>JDBCResourceParameters</class>
8
      </extends>
9
      <fields>
10
        <field name="JDBCDriverClass" type="string" mandatory="true"
11
          defaultValue="org.postgresql.Driver" group="Advanced">
12
          <description>JDBC Driver class</description>
13
        </field>
14
		<field name="port" type="integer" mandatory="false"
15
          defaultValue="5432" group="Connection">
16
          <description></description>
17
        </field>
18
        <field name="host" type="string" mandatory="false" 
19
            defaultValue="127.0.0.1" group="Connection">
20
          <description></description>
21
        </field>
22
        <field name="UseSSL" type="boolean" mandatory="false"
23
          defaultValue="false" group="Basic">
24
          <description>Use SSL connetion</description>
25
        </field>
26
      </fields>
27
    </class>
28

  
29
    <class name="PostgreSQLStoreParameters">
30
      <extends>
31
        <class>JDBCStoreParameters</class>
32
        <class>PostgreSQLResourceParameters</class>
33
      </extends>
34
      <fields/>
35
    </class>
36

  
37
    <class name="PostgreSQLNewStoreParameters">
38
      <extends>
39
        <class>JDBCNewStoreParameters</class>
40
        <class>PostgreSQLResourceParameters</class>
41
      </extends>
42
      <fields/>
43
    </class>
44

  
45

  
46
    <class name="PostgreSQLServerExplorerParameters">
47
      <extends>
48
        <class>PostgreSQLResourceParameters</class>
49
        <class>JDBCServerExplorerParameters</class>
50
      </extends>
51
      <fields/>
52
    </class>
53

  
54

  
55
  </classes>
56
</definitions>  
tags/org.gvsig.postgresql-2.0.65/org.gvsig.postgresql.provider/src/main/java/org/gvsig/fmap/dal/store/postgresql/PostgreSQLNewStoreParameters.java
1
/* gvSIG. Geographic Information System of the Valencian Government
2
 *
3
 * Copyright (C) 2007-2008 Infrastructures and Transports Department
4
 * of the Valencian Government (CIT)
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 2
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 */
22
package org.gvsig.fmap.dal.store.postgresql;
23

  
24
import org.gvsig.fmap.dal.feature.EditableFeatureType;
25
import org.gvsig.fmap.dal.feature.FeatureType;
26
import org.gvsig.fmap.dal.feature.NewFeatureStoreParameters;
27
import org.gvsig.fmap.dal.store.jdbc.JDBCNewStoreParameters;
28

  
29
public class PostgreSQLNewStoreParameters extends JDBCNewStoreParameters
30
        implements NewFeatureStoreParameters, PostgreSQLConnectionParameters {
31

  
32
    public static final String PARAMETERS_DEFINITION_NAME = "PostgreSQLNewStoreParameters";
33

  
34
    public PostgreSQLNewStoreParameters() {
35
        super(PARAMETERS_DEFINITION_NAME, PostgreSQLStoreProvider.NAME);
36
    }
37

  
38
    public EditableFeatureType getDefaultFeatureType() {
39
        return (EditableFeatureType) this.getDynValue(FEATURETYPE_PARAMTER_NAME);
40
    }
41

  
42
    public void setDefaultFeatureType(FeatureType featureType) {
43
        this.setDynValue(FEATURETYPE_PARAMTER_NAME, featureType);
44
    }
45

  
46
    public Boolean getUseSSL() {
47
        return (Boolean) this.getDynValue(DYNFIELDNAME_USESSL);
48
    }
49

  
50
    public void setUseSSL(Boolean useSSL) {
51
        this.setDynValue(DYNFIELDNAME_USESSL, useSSL);
52
    }
53

  
54
}
tags/org.gvsig.postgresql-2.0.65/org.gvsig.postgresql.provider/src/main/java/org/gvsig/fmap/dal/store/postgresql/PostgreSQLResourceParameters.java
1
/* gvSIG. Geographic Information System of the Valencian Government
2
*
3
* Copyright (C) 2007-2008 Infrastructures and Transports Department
4
* of the Valencian Government (CIT)
5
*
6
* This program is free software; you can redistribute it and/or
7
* modify it under the terms of the GNU General Public License
8
* as published by the Free Software Foundation; either version 2
9
* of the License, or (at your option) any later version.
10
*
11
* This program is distributed in the hope that it will be useful,
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
* GNU General Public License for more details.
15
*
16
* You should have received a copy of the GNU General Public License
17
* along with this program; if not, write to the Free Software
18
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
* MA  02110-1301, USA.
20
*
21
*/
22

  
23
/*
24
* AUTHORS (In addition to CIT):
25
* 2009 IVER T.I   {{Task}}
26
*/
27

  
28
package org.gvsig.fmap.dal.store.postgresql;
29

  
30
import org.gvsig.fmap.dal.store.jdbc.JDBCResourceParameters;
31

  
32
public class PostgreSQLResourceParameters extends JDBCResourceParameters
33
		implements PostgreSQLConnectionParameters {
34

  
35
	public static final String PARAMETERS_DEFINITION_NAME = "PostgreSQLResourceParameters";
36

  
37
	public PostgreSQLResourceParameters() {
38
		super(PARAMETERS_DEFINITION_NAME,PostgreSQLResource.NAME);
39
	}
40

  
41
    public PostgreSQLResourceParameters(String url, String host, Integer port,
42
			String dbName, String user, String password,
43
			String jdbcDriverClassName, Boolean ssl) {
44
		super(PARAMETERS_DEFINITION_NAME,PostgreSQLResource.NAME,url, host, port, dbName, user, password, jdbcDriverClassName);
45
		if (ssl != null) {
46
			this.setUseSSL(ssl.booleanValue());
47
		}
48
	}
49

  
50
	public String getUrl() {
51
		return PostgreSQLLibrary.getJdbcUrl(getHost(),
52
				getPort(),
53
				getDBName());
54
	}
55

  
56
	public Boolean getUseSSL() {
57
		return (Boolean) this.getDynValue(DYNFIELDNAME_USESSL);
58
	}
59

  
60
	public void setUseSSL(Boolean useSSL) {
61
		this.setDynValue(DYNFIELDNAME_USESSL, useSSL);
62
	}
63

  
64
	public void setUseSSL(boolean useSSL) {
65
		this.setDynValue(DYNFIELDNAME_USESSL, new Boolean(useSSL));
66
	}
67

  
68
}
tags/org.gvsig.postgresql-2.0.65/org.gvsig.postgresql.provider/src/main/java/org/gvsig/fmap/dal/store/postgresql/PostgreSQLServerExplorerParameters.java
1
/* gvSIG. Geographic Information System of the Valencian Government
2
*
3
* Copyright (C) 2007-2008 Infrastructures and Transports Department
4
* of the Valencian Government (CIT)
5
*
6
* This program is free software; you can redistribute it and/or
7
* modify it under the terms of the GNU General Public License
8
* as published by the Free Software Foundation; either version 2
9
* of the License, or (at your option) any later version.
10
*
11
* This program is distributed in the hope that it will be useful,
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
* GNU General Public License for more details.
15
*
16
* You should have received a copy of the GNU General Public License
17
* along with this program; if not, write to the Free Software
18
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
* MA  02110-1301, USA.
20
*
21
*/
22

  
23
/*
24
* AUTHORS (In addition to CIT):
25
* 2009 IVER T.I   {{Task}}
26
*/
27

  
28
/**
29
 *
30
 */
31
package org.gvsig.fmap.dal.store.postgresql;
32

  
33
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
34
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
35

  
36
public class PostgreSQLServerExplorerParameters extends
37
		JDBCServerExplorerParameters implements PostgreSQLConnectionParameters {
38

  
39

  
40
	public static final String PARAMETERS_DEFINITION_NAME = "PostgreSQLServerExplorerParameters";
41

  
42
	public PostgreSQLServerExplorerParameters() {
43
		super(PARAMETERS_DEFINITION_NAME, PostgreSQLServerExplorer.NAME);
44
	}
45

  
46
	public Boolean getUseSSL() {
47
		return (Boolean) this.getDynValue(DYNFIELDNAME_USESSL);
48
	}
49

  
50
	public void setUseSSL(Boolean useSSL) {
51
		this.setDynValue(DYNFIELDNAME_USESSL, useSSL);
52
	}
53

  
54
	public void setUseSSL(boolean useSSL) {
55
		this.setDynValue(DYNFIELDNAME_USESSL, new Boolean(useSSL));
56
	}
57

  
58
	public void validate() throws ValidateDataParametersException {
59
		if (getJDBCDriverClassName() == null) {
60
			setJDBCDriverClassName(PostgreSQLLibrary.DEFAULT_JDCB_DRIVER_NAME);
61
		}
62
		if (getUrl() == null) {
63
			setUrl(PostgreSQLLibrary.getJdbcUrl(getHost(), getPort(),
64
					getDBName()));
65
		}
66

  
67
		if (getPort() == null) {
68
			setPort(new Integer(5432));
69
		}
70
		super.validate();
71
	}
72

  
73
}
tags/org.gvsig.postgresql-2.0.65/org.gvsig.postgresql.provider/src/main/java/org/gvsig/fmap/dal/store/postgresql/PostgreSQLHelper.java
1
/* gvSIG. Geographic Information System of the Valencian Government
2
*
3
* Copyright (C) 2007-2008 Infrastructures and Transports Department
4
* of the Valencian Government (CIT)
5
*
6
* This program is free software; you can redistribute it and/or
7
* modify it under the terms of the GNU General Public License
8
* as published by the Free Software Foundation; either version 2
9
* of the License, or (at your option) any later version.
10
*
11
* This program is distributed in the hope that it will be useful,
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
* GNU General Public License for more details.
15
*
16
* You should have received a copy of the GNU General Public License
17
* along with this program; if not, write to the Free Software
18
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
* MA  02110-1301, USA.
20
*
21
*/
22

  
23
/*
24
* AUTHORS (In addition to CIT):
25
* 2009 IVER T.I   {{Task}}
26
*/
27

  
28
/**
29
 *
30
 */
31
package org.gvsig.fmap.dal.store.postgresql;
32

  
33
import java.sql.Connection;
34
import java.sql.DatabaseMetaData;
35
import java.sql.PreparedStatement;
36
import java.sql.ResultSet;
37
import java.sql.ResultSetMetaData;
38
import java.sql.SQLException;
39
import java.sql.Statement;
40
import java.util.ArrayList;
41
import java.util.Comparator;
42
import java.util.Date;
43
import java.util.Iterator;
44
import java.util.List;
45
import java.util.Map;
46
import java.util.Properties;
47
import java.util.TreeMap;
48
import java.util.TreeSet;
49

  
50
import org.apache.commons.lang3.StringUtils;
51
import org.cresques.cts.IProjection;
52
import org.gvsig.fmap.crs.CRSFactory;
53
import org.gvsig.fmap.dal.DALLocator;
54
import org.gvsig.fmap.dal.DataTypes;
55
import org.gvsig.fmap.dal.NewDataStoreParameters;
56
import org.gvsig.fmap.dal.exception.DataException;
57
import org.gvsig.fmap.dal.exception.InitializeException;
58
import org.gvsig.fmap.dal.exception.ReadException;
59
import org.gvsig.fmap.dal.exception.WriteException;
60
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
61
import org.gvsig.fmap.dal.feature.EditableFeatureType;
62
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
63
import org.gvsig.fmap.dal.feature.FeatureType;
64
import org.gvsig.fmap.dal.feature.exception.CreateGeometryException;
65
import org.gvsig.fmap.dal.feature.exception.UnsupportedDataTypeException;
66
import org.gvsig.fmap.dal.resource.ResourceAction;
67
import org.gvsig.fmap.dal.resource.spi.ResourceManagerProviderServices;
68
import org.gvsig.fmap.dal.store.jdbc.ConnectionAction;
69
import org.gvsig.fmap.dal.store.jdbc.JDBCHelper;
70
import org.gvsig.fmap.dal.store.jdbc.JDBCHelperUser;
71
import org.gvsig.fmap.dal.store.jdbc.JDBCNewStoreParameters;
72
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
73
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCException;
74
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecutePreparedSQLException;
75
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecuteSQLException;
76
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCPreparingSQLException;
77
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
78
import org.gvsig.fmap.geom.Geometry;
79
import org.gvsig.fmap.geom.primitive.Envelope;
80
import org.gvsig.tools.ToolsLocator;
81
import org.gvsig.tools.exception.BaseException;
82
import org.postgresql.PGResultSetMetaData;
83
import org.slf4j.Logger;
84
import org.slf4j.LoggerFactory;
85

  
86
/**
87
 * @author jmvivo
88
 *
89
 */
90
public class PostgreSQLHelper extends JDBCHelper {
91

  
92
	private static Logger logger = LoggerFactory
93
			.getLogger(PostgreSQLHelper.class);
94

  
95
	private Map pgSR2SRSID = new TreeMap();
96
	private Map srsID2pgSR = new TreeMap();
97

  
98
	private static Properties beforePostgis13 = null;
99
    private int[] postGISVersion = { 0,0,0 };
100
    private boolean versionSet = false;
101

  
102
	PostgreSQLHelper(JDBCHelperUser consumer,
103
			PostgreSQLConnectionParameters params)
104
			throws InitializeException {
105

  
106
		super(consumer, params);
107
	}
108

  
109
	protected void initializeResource() throws InitializeException {
110
		ResourceManagerProviderServices manager = (ResourceManagerProviderServices) DALLocator
111
		.getResourceManager();
112
		PostgreSQLResource resource = (PostgreSQLResource) manager
113
		.createAddResource(
114
				PostgreSQLResource.NAME, new Object[] {
115
						params.getUrl(), params.getHost(),
116
						params.getPort(), params.getDBName(), params.getUser(),
117
						params.getPassword(),
118
						params.getJDBCDriverClassName(),
119
						((PostgreSQLConnectionParameters) params).getUseSSL() });
120
		this.setResource(resource);
121
	}
122

  
123

  
124
	protected String getDefaultSchema(Connection conn)
125
			throws JDBCException {
126
		if (defaultSchema == null) {
127
			String sql = "Select current_schema()";
128
			ResultSet rs = null;
129
			Statement st = null;
130
			String schema = null;
131
			try {
132
				st = conn.createStatement();
133
				try {
134
					rs = JDBCHelper.executeQuery(st, sql);
135
				} catch (java.sql.SQLException e) {
136
					throw new JDBCExecuteSQLException(sql, e);
137
				}
138
				rs.next();
139
				schema = rs.getString(1);
140
			} catch (java.sql.SQLException e) {
141
				throw new JDBCSQLException(e);
142
			} finally {
143
				try {rs.close();} catch (Exception e) {logger.error("Exception clossing resulset", e);};
144
				try {st.close();} catch (Exception e) {logger.error("Exception clossing statement", e);};
145
				rs = null;
146
				st = null;
147
			}
148
			defaultSchema = schema;
149
		}
150

  
151
		return defaultSchema;
152
	}
153

  
154
    public Envelope getFullEnvelopeOfField(
155
            JDBCStoreParameters storeParams,
156
            String geometryAttrName, Envelope limit)
157
            throws DataException {
158

  
159
        StringBuilder strb = new StringBuilder();
160
        strb.append("Select " + getFunctionName("ST_AsEWKB") + "("
161
                + getFunctionName("ST_Extent") + "(");
162
        strb.append(escapeFieldName(geometryAttrName));
163
        strb.append(")) from ");
164

  
165
        if (storeParams.getSQL() != null
166
                && storeParams.getSQL().trim().length() > 0) {
167
            strb.append('(');
168
            strb.append(storeParams.getSQL());
169
            strb.append(") as _subquery_alias_ ");
170
        } else {
171
            strb.append(storeParams.tableID());
172
        }
173

  
174
        if (limit != null || (storeParams.getBaseFilter() != null
175
                && storeParams.getBaseFilter().trim().length() > 0)) {
176
            strb.append(" where  ");
177

  
178
            if (limit != null) {
179
                strb.append(" ( " + getFunctionName("ST_Intersects") + "("
180
                        + getFunctionName("ST_GeomFromText") + "('");
181
                String workAreaWkt = null;
182
                try {
183
                    workAreaWkt = limit.getGeometry().convertToWKT();
184
                } catch (Exception e) {
185
                    throw new CreateGeometryException(e);
186
                }
187
                strb.append(workAreaWkt);
188
                strb.append("', ");
189

  
190
                IProjection proj = storeParams.getCRS();
191
                int sridInt = this.getProviderSRID(proj);
192
                if (sridInt == -1) {
193
                    throw new CreateGeometryException(
194
                            new Exception("CRS is null or unknown."));
195
                } else {
196
                    strb.append(Integer.toString(sridInt));
197
                }
198
                strb.append("), " + getFunctionName("ST_Envelope") + "(");
199
                strb.append(escapeFieldName(geometryAttrName));
200
                strb.append(")) ) ");
201

  
202
            }
203
            if (storeParams.getBaseFilter() != null && storeParams.getBaseFilter().trim().length() > 0) {
204
                if (limit != null) {
205
                    strb.append(" and ");
206
                }
207
                strb.append(" ( ");
208
                strb.append(storeParams.getBaseFilter());
209
                strb.append(" ) ");
210
            }
211

  
212
        }
213

  
214
        final String sql = strb.toString();
215

  
216
        this.open();
217

  
218
        return (Envelope) getResource().execute(new ResourceAction() {
219
            public String toString() {
220
                return "getEnvelope";
221
            }
222

  
223
            public Object run() throws Exception {
224
                ResultSet rs = null;
225
                Statement st = null;
226
                Connection conn = null;
227
                Envelope fullEnvelope = null;
228

  
229
                Envelope emptyEnv
230
                        = geomManager.createEnvelope(Geometry.SUBTYPES.GEOM2D);
231

  
232
                try {
233

  
234
                    conn = getConnection();
235
                    st = conn.createStatement();
236
                    try {
237
                        rs = JDBCHelper.executeQuery(st, sql);
238
                    } catch (java.sql.SQLException e) {
239
                        throw new JDBCExecuteSQLException(sql, e);
240
                    }
241
                    if (!rs.next()) {
242
                        return emptyEnv;
243
                    }
244

  
245
                    byte[] data = rs.getBytes(1);
246
                    if (data == null) {
247
                        return emptyEnv;
248
                    }
249

  
250
                    Geometry geom = geomManager.createFrom(data);
251

  
252
                    fullEnvelope = geom.getEnvelope();
253

  
254
                    return fullEnvelope;
255
                } catch (java.sql.SQLException e) {
256
                    throw new JDBCSQLException(e);
257
                } catch (BaseException e) {
258
                    throw new ReadException(user.getProviderName(), e);
259
                } finally {
260
                    try {
261
                        rs.close();
262
                    } catch (Exception e) {
263
                    }
264
                    try {
265
                        st.close();
266
                    } catch (Exception e) {
267
                    }
268
                    try {
269
                        conn.close();
270
                    } catch (Exception e) {
271
                    }
272
                    rs = null;
273
                    st = null;
274
                    conn = null;
275
                }
276
            }
277
        });
278
    }
279
    
280
    @Override
281
    public Object dalValueToJDBC(FeatureAttributeDescriptor attributeDescriptor, Object value)
282
            throws WriteException {
283

  
284
        try {
285
            if (value == null) {
286
                return null;
287
            }
288
            Date jdate = null;
289
            switch (attributeDescriptor.getType()) {
290
                case DataTypes.DATE:
291
                    jdate = (Date)value;
292
                    java.sql.Date sqldate = new java.sql.Date(jdate.getTime());
293
                    return sqldate;
294
                    
295
                case DataTypes.TIME:
296
                    jdate = (Date)value;
297
                    java.sql.Time sqltime = new java.sql.Time(jdate.getTime());
298
                    return sqltime;
299

  
300
                case DataTypes.GEOMETRY:
301
                    IProjection srs = null;
302
                    byte[] wkb = null;
303
                    Geometry geom = null;
304
                    try {
305
                        geom = (Geometry)value;
306
                        Geometry geom1 = coerce(attributeDescriptor.getGeomType(), geom);
307
                        srs = attributeDescriptor.getSRS();
308
                        if (srs != null) {
309
                            wkb = geom1.convertToEWKBForcingType(getProviderSRID(srs), attributeDescriptor.getGeomType().getType());
310
                        } else {
311
                            wkb = geom1.convertToEWKB();
312
                        }
313
                    } catch (Exception e) {
314
                        String problem = "";
315
                        if (geom != null) {
316
                            Geometry.ValidationStatus vs = geom.getValidationStatus();
317
                            problem = vs.getMessage();
318
                        }
319
                        throw new DalValueToJDBCException(attributeDescriptor, value, problem, e);
320
                    }
321
                    return wkb;
322
                
323
                default:
324
                    return value;
325
            }
326
            
327
        } catch(DalValueToJDBCException ex) {
328
            throw ex;
329
        } catch (Exception e) {
330
            throw new DalValueToJDBCException(attributeDescriptor, value, e);
331
        }
332

  
333
    }
334

  
335
	@Override
336
	protected boolean supportsGeometry() {
337
		return true;
338
	}
339

  
340
	/**
341
	 * Fill <code>featureType</code> geometry attributes with SRS and ShapeType
342
	 * information stored in the table GEOMETRY_COLUMNS
343
	 *
344
	 * @param conn
345
	 * @param rsMetadata
346
	 * @param featureType
347
	 * @throws ReadException
348
	 */
349
	protected void loadSRS_and_shapeType(Connection conn,
350
			ResultSetMetaData rsMetadata, EditableFeatureType featureType,
351
			String baseSchema, String baseTable)
352
			throws JDBCException {
353

  
354
		Statement st = null;
355
		ResultSet rs = null;
356
		try {
357
			// Sacamos la lista de los attributos geometricos
358
			EditableFeatureAttributeDescriptor attr;
359
			List geoAttrs = new ArrayList();
360

  
361
			Iterator iter = featureType.iterator();
362
			while (iter.hasNext()) {
363
				attr = (EditableFeatureAttributeDescriptor) iter.next();
364
				if (attr.getType() == DataTypes.GEOMETRY) {
365
					geoAttrs.add(attr);
366
				}
367
			}
368
			if (geoAttrs.size() < 1) {
369
				return;
370
			}
371

  
372

  
373
			// preparamos un set con las lista de tablas de origen
374
			// de los campos
375
			class TableId {
376
				public String schema=null;
377
				public String table=null;
378
				public String field = null;
379

  
380
				public void appendToSQL(StringBuilder strb) {
381
					if (schema == null || schema.length() == 0) {
382
						strb
383
								.append("( F_TABLE_SCHEMA = current_schema() AND F_TABLE_NAME = '");
384
					} else {
385
						strb.append("( F_TABLE_SCHEMA = '");
386
						strb.append(schema);
387
						strb.append("' AND F_TABLE_NAME = '");
388
					}
389
					strb.append(table);
390
					strb.append("' AND F_GEOMETRY_COLUMN = '");
391
					strb.append(field);
392
					strb.append("' )");
393
				}
394

  
395
			}
396
			Comparator cmp = new Comparator(){
397
				public int compare(Object arg0, Object arg1) {
398
					TableId a0 = (TableId) arg0;
399
					TableId a1 = (TableId) arg1;
400

  
401
					int aux = a0.field.compareTo(a1.field);
402
					if (aux != 0) {
403
					    return aux;
404
					}
405

  
406
					aux = a0.table.compareTo(a1.table);
407
                    if (aux != 0) {
408
                        return aux;
409
                    }
410

  
411
                    if (a0.schema == null) {
412
                        if (a1.schema == null) {
413
                            aux = 0;
414
                        } else {
415
                            aux = -1;
416
                        }
417
                    } else {
418
                        if (a1.schema == null) {
419
                            aux = -1;
420
                        } else {
421
                            aux = a0.schema.compareTo(a1.schema);
422
                        }
423
                    }
424
					return aux;
425
				}
426
			};
427
			TreeSet set = new TreeSet(cmp);
428
			TableId tableId;
429
			iter = geoAttrs.iterator();
430
			int rsIndex;
431
			while (iter.hasNext()) {
432
				attr = (EditableFeatureAttributeDescriptor) iter.next();
433
				tableId = new TableId();
434
				rsIndex = attr.getIndex() + 1;
435

  
436
				if (baseSchema == null && baseTable == null) {
437
					if (rsMetadata instanceof PGResultSetMetaData) {
438
						tableId.schema = ((PGResultSetMetaData) rsMetadata)
439
								.getBaseSchemaName(rsIndex);
440
						tableId.table = ((PGResultSetMetaData) rsMetadata)
441
								.getBaseTableName(rsIndex);
442
						tableId.field = ((PGResultSetMetaData) rsMetadata)
443
								.getBaseColumnName(rsIndex);
444

  
445
					} else {
446
						tableId.schema = rsMetadata.getSchemaName(rsIndex);
447
						tableId.table = rsMetadata.getTableName(rsIndex);
448
						tableId.field = rsMetadata.getColumnName(rsIndex);
449
					}
450
				} else {
451
					tableId.schema = baseSchema;
452
					tableId.table = baseTable;
453
					tableId.field = rsMetadata.getColumnName(rsIndex);
454
				}
455
				if (tableId.table == null || tableId.table.length() == 0) {
456
					// Si no tiene tabla origen (viene de algun calculo por ej.)
457
					// lo saltamos ya que no estara en la tabla GEOMETRY_COLUMNS
458
					continue;
459
				}
460
				set.add(tableId);
461
			}
462

  
463
			if (set.size() == 0) {
464
				return;
465
			}
466

  
467
			// Preparamos una sql para que nos saque el resultado
468
			StringBuilder strb = new StringBuilder();
469
			strb.append("Select geometry_columns.*,auth_name || ':' || auth_srid as SRSID ");
470
			strb.append("from geometry_columns left join spatial_ref_sys on ");
471
			strb.append("geometry_columns.srid = spatial_ref_sys.srid WHERE ");
472
			iter = set.iterator();
473
			for (int i=0;i<set.size()-1;i++) {
474
				tableId = (TableId) iter.next();
475
				tableId.appendToSQL(strb);
476
				strb.append(" OR ");
477
			}
478
			tableId = (TableId) iter.next();
479
			tableId.appendToSQL(strb);
480
			String sql = strb.toString();
481

  
482

  
483
			st = conn.createStatement();
484
			try {
485
				rs = JDBCHelper.executeQuery(st,sql);
486
			} catch (SQLException e) {
487
				throw new JDBCExecuteSQLException(sql, e);
488
			}
489
			String srsID;
490
			int pgSrid;
491
			int geometryType;
492
			int geometrySubtype;
493
			String geomTypeStr;
494
			int dimensions;
495
			IProjection srs;
496

  
497
			while (rs.next()){
498
				srsID = rs.getString("SRSID");
499
				pgSrid = rs.getInt("SRID");
500
				geomTypeStr = rs.getString("TYPE").toUpperCase();
501
				geometryType = Geometry.TYPES.GEOMETRY;
502
				if (geomTypeStr.startsWith("POINT")) {
503
					geometryType = Geometry.TYPES.POINT;
504
				} else if (geomTypeStr.startsWith("LINESTRING")) {
505
					geometryType = Geometry.TYPES.CURVE;
506
				} else if (geomTypeStr.startsWith("POLYGON")) {
507
					geometryType = Geometry.TYPES.SURFACE;
508
				} else if (geomTypeStr.startsWith("MULTIPOINT")) {
509
					geometryType = Geometry.TYPES.MULTIPOINT;
510
				} else if (geomTypeStr.startsWith("MULTILINESTRING")) {
511
					geometryType = Geometry.TYPES.MULTICURVE;
512
				} else if (geomTypeStr.startsWith("MULTIPOLYGON")) {
513
					geometryType = Geometry.TYPES.MULTISURFACE;
514
				}
515
				dimensions = rs.getInt("coord_dimension");
516
				geometrySubtype = Geometry.SUBTYPES.GEOM2D;
517
				if (dimensions > 2) {
518
					if (dimensions == 3) {
519
						if (geomTypeStr.endsWith("M")) {
520
							geometrySubtype = Geometry.SUBTYPES.GEOM2DM;
521
						} else {
522
							geometrySubtype = Geometry.SUBTYPES.GEOM3D;
523
						}
524

  
525
					} else {
526
						geometrySubtype = Geometry.SUBTYPES.GEOM3DM;
527
					}
528
				}
529
				addToPgSRToSRSID(pgSrid, srsID);
530

  
531

  
532
				iter = geoAttrs.iterator();
533
				while (iter.hasNext()) {
534
					attr = (EditableFeatureAttributeDescriptor) iter.next();
535
					rsIndex = attr.getIndex() + 1;
536
					if (!rsMetadata.getColumnName(rsIndex).equals(
537
							rs.getString("f_geometry_column"))) {
538
						continue;
539
					}
540

  
541
					if (baseSchema == null && baseTable == null) {
542

  
543
						if (rsMetadata instanceof PGResultSetMetaData) {
544
							if (!((PGResultSetMetaData) rsMetadata)
545
									.getBaseTableName(rsIndex).equals(
546
											rs.getString("f_table_name"))) {
547
								continue;
548
							}
549
							String curSchema = rs.getString("f_table_schema");
550
							String metaSchema = ((PGResultSetMetaData) rsMetadata)
551
									.getBaseSchemaName(rsIndex);
552
							if (!metaSchema.equals(curSchema)) {
553
								if (metaSchema.length() == 0
554
										&& metaSchema == getDefaultSchema(conn)) {
555
								} else {
556
									continue;
557
								}
558
							}
559

  
560
						} else {
561

  
562
							if (!rsMetadata.getTableName(rsIndex).equals(
563
									rs.getString("f_table_name"))) {
564
								continue;
565
							}
566
							String curSchema = rs.getString("f_table_schema");
567
							String metaSchema = rsMetadata
568
									.getSchemaName(rsIndex);
569
							if (!metaSchema.equals(curSchema)) {
570
								if (metaSchema.length() == 0
571
										&& metaSchema == getDefaultSchema(conn)) {
572
								} else {
573
									continue;
574
								}
575
							}
576
						}
577
					}
578
					attr.setGeometryType(geometryType);
579
					attr.setGeometrySubType(geometrySubtype);
580
					if (srsID != null && srsID.length() > 0) {
581
						attr.setSRS(CRSFactory.getCRS(srsID));
582
					}
583
					iter.remove();
584
				}
585
				iter = geoAttrs.iterator();
586
				while (iter.hasNext()) {
587
					attr = (EditableFeatureAttributeDescriptor) iter.next();
588
					attr.setSRS(null);
589
					attr.setGeometryType(Geometry.TYPES.GEOMETRY);
590

  
591
				}
592
			}
593

  
594
		} catch (java.sql.SQLException e) {
595
			throw new JDBCSQLException(e);
596
		} finally {
597
			try {rs.close();} catch (Exception e) {	};
598
			try {st.close();} catch (Exception e) {	};
599
		}
600

  
601
	}
602

  
603

  
604
	public String getSqlColumnTypeDescription(FeatureAttributeDescriptor attr) {
605
		if (attr.getType() == DataTypes.GEOMETRY) {
606
			return "geometry";
607
		}
608
		return super.getSqlColumnTypeDescription(attr);
609
	}
610

  
611

  
612
	public int getPostgisGeomDimensions(int geometrySubType) {
613
		switch (geometrySubType) {
614
		case Geometry.SUBTYPES.GEOM2D:
615
			return 2;
616
		case Geometry.SUBTYPES.GEOM2DM:
617
		case Geometry.SUBTYPES.GEOM3D:
618
			return 3;
619

  
620
		case Geometry.SUBTYPES.GEOM3DM:
621
			return 4;
622
		default:
623
			throw new UnsupportedDataTypeException(
624
					ToolsLocator.getDataTypesManager().getTypeName(DataTypes.GEOMETRY),
625
					DataTypes.GEOMETRY);
626
		}
627
	}
628

  
629
	public String getPostgisGeomType(int geometryType, int geometrySubType) {
630
		String pgGeomType;
631
		switch (geometryType) {
632
		case Geometry.TYPES.GEOMETRY:
633
			pgGeomType = "GEOMETRY";
634
			break;
635
		case Geometry.TYPES.POINT:
636
			pgGeomType = "POINT";
637
			break;
638
		case Geometry.TYPES.CURVE:
639
			pgGeomType = "LINESTRING";
640
			break;
641
		case Geometry.TYPES.SURFACE:
642
			pgGeomType = "POLYGON";
643
			break;
644
		case Geometry.TYPES.MULTIPOINT:
645
			pgGeomType = "MULTIPOINT";
646
			break;
647
		case Geometry.TYPES.MULTICURVE:
648
			pgGeomType = "MULTILINESTRING";
649
			break;
650
		case Geometry.TYPES.MULTISURFACE:
651
			pgGeomType = "MULTIPOLYGON";
652
			break;
653
		default:
654
                    logger.warn("Can't determine PostGIS geometry type, use GEOMETRY.");
655
                    pgGeomType = "GEOMETRY";
656
		}
657
		if (geometrySubType == Geometry.SUBTYPES.GEOM2DM
658
				|| geometrySubType == Geometry.SUBTYPES.GEOM3DM) {
659
			pgGeomType = pgGeomType + "M";
660
		} /* else  if (geometrySubType == Geometry.SUBTYPES.GEOM3D) {
661
			throw new UnsupportedGeometryException(geometryType,
662
					geometrySubType);
663
                   /
664
		} */
665
		return pgGeomType;
666
	}
667

  
668
	public int getProviderSRID(String srs) {
669
		if (srs != null) {
670
			Integer pgSRID = (Integer) srsID2pgSR.get(srs);
671
			if (pgSRID != null) {
672
				return pgSRID.intValue();
673
			}
674

  
675
			return searchpgSRID(srs);
676

  
677
		}
678
		return -1;
679
	}
680

  
681

  
682
	public int getProviderSRID(IProjection srs) {
683
		if (srs != null) {
684
			Integer pgSRID = (Integer) srsID2pgSR.get(srs.getAbrev());
685
			if (pgSRID != null) {
686
				return pgSRID.intValue();
687
			}
688

  
689
			return searchpgSRID(srs);
690

  
691
		}
692
		return -1;
693
	}
694

  
695
	private int searchpgSRID(final IProjection srs) {
696
		if (srs == null) {
697
			return -1;
698
		}
699
		return searchpgSRID(srs.getAbrev());
700
	}
701

  
702
	private int searchpgSRID(final String srsID) {
703
		if (srsID == null) {
704
			return -1;
705
		}
706

  
707
		ConnectionAction action = new ConnectionAction(){
708

  
709
			public Object action(Connection conn) throws DataException {
710

  
711
				String[] abrev = srsID.split(":");
712
				StringBuilder sqlb = new StringBuilder();
713
				sqlb.append("select srid from spatial_ref_sys where ");
714
				if (abrev.length > 1) {
715
					sqlb.append("auth_name = ? and ");
716
				}
717
				sqlb.append("auth_srid = ?");
718

  
719
				String sql = sqlb.toString();
720
				PreparedStatement st;
721
				try {
722
					st = conn.prepareStatement(sql);
723
				} catch (SQLException e){
724
					throw new JDBCPreparingSQLException(sql,e);
725
				}
726
				ResultSet rs = null;
727
				try{
728
					int i=0;
729
					if (abrev.length > 1){
730
						st.setString(i+1, abrev[i]);
731
						i++;
732
					}
733
					st.setInt(i + 1, Integer.parseInt(abrev[i]));
734

  
735
					try{
736
						rs = JDBCHelper.executeQuery(st,sql);
737

  
738
					} catch (SQLException e){
739
						throw new JDBCExecutePreparedSQLException(sql, abrev, e);
740
					}
741

  
742
					if (!rs.next()) {
743
						return null;
744
					}
745

  
746
					return new Integer(rs.getInt(1));
747

  
748
				} catch (SQLException e){
749
					throw new JDBCSQLException(e);
750
				} finally{
751
					try {rs.close(); } catch (Exception e) {};
752
					try {st.close(); } catch (Exception e) {};
753
				}
754

  
755
			}
756

  
757
		};
758

  
759
		Integer pgSRSID = null;
760
		try {
761
			pgSRSID = (Integer) doConnectionAction(action);
762
		} catch (Exception e) {
763
			logger.error("Excetion searching pgSRS", e);
764
			return -1;
765
		}
766

  
767
		if (pgSRSID != null) {
768
			addToPgSRToSRSID(pgSRSID.intValue(), srsID);
769
			return pgSRSID.intValue();
770
		}
771
		return -1;
772

  
773
	}
774

  
775
	private void addToPgSRToSRSID(int pgSRID, String srsId) {
776
		if (pgSRID < 0 || srsId == null || srsId.length() == 0) {
777
			return;
778
		}
779
		Integer pgSRIDInteger = new Integer(pgSRID);
780
		pgSR2SRSID.put(pgSRIDInteger, srsId);
781
		srsID2pgSR.put(srsId, pgSRIDInteger);
782
	}
783

  
784
        public List<String> getSqlGeometyFieldAdd(FeatureAttributeDescriptor attr,
785
                String table, String schema) {
786
                    // SELECT AddGeometryColumn({schema}, {table}, {field}, {srid}(int),
787
            // {geomType}(Str), {dimensions}(int))
788

  
789
                    // gemoType:
790
                    /*
791
             * POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING,
792
             * MULTIPOLYGON, GEOMETRYCOLLECTION POINTM, LINESTRINGM, POLYGONM,
793
             * MULTIPOINTM, MULTILINESTRINGM, MULTIPOLYGONM, GEOMETRYCOLLECTIONM
794
             */
795
            List<String> sqls = new ArrayList<String>();
796

  
797
            StringBuilder strb = new StringBuilder();
798
            strb.append("SELECT AddGeometryColumn('");
799
            if ( schema != null && schema.length() > 0 ) {
800
                strb.append(schema);
801
                strb.append("', '");
802
            }
803
            strb.append(table);
804
            strb.append("', '");
805
            strb.append(attr.getName().toLowerCase());
806
            strb.append("', ");
807
            strb.append(getProviderSRID(attr.getSRS()));
808
            strb.append(", '");
809

  
810
            strb.append(getPostgisGeomType(
811
                    attr.getGeometryType(),
812
                    attr.getGeometrySubType()
813
            )
814
            );
815
            strb.append("', ");
816
            strb.append(getPostgisGeomDimensions(attr.getGeometrySubType()));
817
            strb.append(")");
818

  
819
            sqls.add(strb.toString());
820

  
821
            return sqls;
822
        }
823

  
824
	public String getSqlFieldName(FeatureAttributeDescriptor attribute) {
825
		if (attribute.getType() == DataTypes.GEOMETRY) {
826
			return getFunctionName("ST_AsEWKB") + "("
827
			    + super.getSqlFieldName(attribute) + ")";
828
		}
829
		return super.getSqlFieldName(attribute);
830
	}
831

  
832
	protected EditableFeatureAttributeDescriptor createAttributeFromJDBC(
833
			EditableFeatureType type, Connection conn,
834
			ResultSetMetaData rsMetadata, int colIndex) throws SQLException {
835
		if (rsMetadata.getColumnType(colIndex) == java.sql.Types.OTHER) {
836
			if (rsMetadata.getColumnTypeName(colIndex).equalsIgnoreCase(
837
					"geometry")) {
838
				EditableFeatureAttributeDescriptor attr = type.add(rsMetadata.getColumnName(colIndex),
839
						DataTypes.GEOMETRY);
840
				// Set default values for geometry type
841
		                attr.setGeometryType(Geometry.TYPES.GEOMETRY);
842
		                attr.setGeometrySubType(Geometry.SUBTYPES.GEOM2D);
843
		                return attr;
844

  
845
			}
846
		}
847

  
848
		return super.createAttributeFromJDBC(type, conn, rsMetadata, colIndex);
849
	}
850

  
851
	public List getAdditionalSqlToCreate(NewDataStoreParameters ndsp,
852
			FeatureType fType) {
853
		FeatureAttributeDescriptor attr;
854
		Iterator iter = fType.iterator();
855
		List result = new ArrayList();
856
		PostgreSQLNewStoreParameters pgNdsp = (PostgreSQLNewStoreParameters) ndsp;
857
		while (iter.hasNext()){
858
			attr = (FeatureAttributeDescriptor) iter.next();
859
			if (attr.getType() == DataTypes.GEOMETRY){
860
				result.addAll(getSqlGeometyFieldAdd(attr, pgNdsp.getTable(),
861
						pgNdsp
862
						.getSchema()));
863
			}
864
                        if( attr.isIndexed() ) {
865
                            result.add(getCreateIndexStatement((JDBCNewStoreParameters) ndsp, attr));
866
                        }
867
                        if( attr.isAutomatic() ) {
868
                            // A?adimos los GRANT para la secuencia asociada a la tabla.
869
                            String table = "\""+pgNdsp.getSchema() +"\".\""+pgNdsp.getTable()+"_"+attr.getName()+"_seq\" ";
870
                            result.addAll(this.createGrantStatements(pgNdsp, table));
871
                        }
872
		}
873

  
874

  
875
		return result;
876
	}
877

  
878
        protected String getCreateIndexStatement(JDBCNewStoreParameters params,FeatureAttributeDescriptor attr ) {
879
            String indexName = "idx_"+params.getTable()+"_"+attr.getName();
880

  
881
            String statement = "CREATE ";
882
            if( !attr.allowIndexDuplicateds() ) {
883
                statement += " UNIQUE ";
884
            }
885
            statement += "INDEX \""+indexName+"\" ";
886
            statement += "ON " + params.tableID() + " ";
887
            if( attr.getType()==DataTypes.GEOMETRY ) {
888
                statement += " USING GIST ";
889
                statement += "( \"" + attr.getName()+ "\")";
890
            } else {
891
                statement += "( \"" + attr.getName()+ "\"";
892
                if( attr.isIndexAscending() ) {
893
                    statement += " ASC )";
894
                } else {
895
                    statement += " DESC )";
896
                }
897
            }
898
            return statement;
899
        }
900

  
901
	public String getSqlFieldDescription(FeatureAttributeDescriptor attr)
902
			throws DataException {
903
		if (attr.getType() == DataTypes.GEOMETRY){
904
			return null;
905
		}
906
		return super.getSqlFieldDescription(attr);
907
	}
908

  
909

  
910
	public boolean allowAutomaticValues() {
911
		return Boolean.TRUE;
912
	}
913

  
914
	public boolean supportOffset() {
915
		return true;
916
	}
917

  
918
	public boolean supportsUnion() {
919
		return true;
920
	}
921

  
922
	public String escapeFieldName(String field) {
923
		/*
924
		if (!reservedWord(field) &&
925
				field.matches("[a-z][a-z0-9_]*")) {
926
			return field;
927
		}
928
		*/
929
		String quote = getIdentifierQuoteString();
930
		return quote + field + quote;
931
	}
932

  
933
    protected EditableFeatureAttributeDescriptor createAttributeFromJDBCNativeType(
934
        EditableFeatureType fType, ResultSetMetaData rsMetadata, int colIndex)
935
        throws SQLException {
936

  
937
        EditableFeatureAttributeDescriptor column;
938

  
939
        String nativeType = rsMetadata.getColumnTypeName(colIndex);
940

  
941
        if (nativeType.startsWith("int")) {
942
            column = fType.add(rsMetadata.getColumnName(colIndex),
943
                DataTypes.INT);
944
            column.setAdditionalInfo("SQLType", new Integer(rsMetadata
945
                .getColumnType(colIndex)));
946
            column.setAdditionalInfo("SQLTypeName", rsMetadata
947
                .getColumnTypeName(colIndex));
948
            return column;
949
        }
950
        return super.createAttributeFromJDBCNativeType(fType, rsMetadata, colIndex);
951
    }
952

  
953

  
954
    // =======================================
955

  
956

  
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff