Revision 1045

View differences:

tags/org.gvsig.postgresql-2.0.202/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.202</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.365</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.202</connection>
20
      <developerConnection>scm:svn:https://devel.gvsig.org/svn/gvsig-postgresql/tags/org.gvsig.postgresql-2.0.202</developerConnection>
21
      <url>https://devel.gvsig.org/redmine/projects/gvsig-postgresql/repository/show/tags/org.gvsig.postgresql-2.0.202</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.202</version>
63
          </dependency>
64
          <dependency>
65
            <groupId>org.gvsig</groupId>
66
            <artifactId>org.gvsig.postgresql.app.mainplugin</artifactId>
67
            <version>2.0.202</version>
68
          </dependency>
69
        <dependency>
70
            <groupId>org.postgresql</groupId>
71
            <artifactId>postgresql</artifactId>
72
            <version>42.3.1</version>
73
        </dependency>
74
        <dependency>
75
          <groupId>org.apache.commons</groupId>
76
          <artifactId>commons-dbcp2</artifactId>
77
          <version>2.7.0</version>
78
        </dependency>   
79
        <dependency>
80
            <groupId>org.apache.commons</groupId>
81
            <artifactId>commons-pool2</artifactId>
82
            <version>2.7.0</version>
83
        </dependency>
84
      </dependencies>
85
  </dependencyManagement>
86
 
87
  <modules>
88
    <module>org.gvsig.postgresql.app</module>
89
    <module>org.gvsig.postgresql.provider</module>
90
  </modules>
91

  
92
</project>
tags/org.gvsig.postgresql-2.0.202/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/PostgreSQLHelper.java
1

  
2
package org.gvsig.postgresql.dal;
3

  
4
import java.sql.Connection;
5
import java.sql.DriverManager;
6
import java.sql.SQLException;
7
import org.apache.commons.dbcp2.BasicDataSource;
8
import org.apache.commons.lang3.BooleanUtils;
9
import org.apache.commons.lang3.StringUtils;
10
import org.gvsig.expressionevaluator.GeometryExpressionBuilderHelper.GeometrySupportType;
11
import org.gvsig.fmap.dal.resource.exception.AccessResourceException;
12
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters;
13
import org.gvsig.fmap.dal.store.jdbc.JDBCNewStoreParameters;
14
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
15
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
16
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCDriverClassNotFoundException;
17
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
18
import org.gvsig.fmap.dal.store.jdbc2.OperationsFactory;
19
import org.gvsig.fmap.dal.store.jdbc2.spi.ConnectionProvider;
20
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCHelperBase;
21
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
22
import org.gvsig.fmap.dal.store.jdbc2.spi.SRSSolverBase;
23
import org.gvsig.fmap.dal.store.jdbc2.spi.SRSSolverDumb;
24
import org.gvsig.postgresql.dal.operations.PostgreSQLOperationsFactory;
25
import org.gvsig.tools.dispose.Disposable;
26
import org.gvsig.tools.exception.BaseException;
27
import org.postgresql.util.DriverInfo;
28
import org.slf4j.Logger;
29
import org.slf4j.LoggerFactory;
30

  
31
@SuppressWarnings("UseSpecificCatch")
32
public class PostgreSQLHelper extends JDBCHelperBase {
33

  
34
    /* friend */ static final Logger LOGGER = LoggerFactory.getLogger(PostgreSQLHelper.class);
35

  
36
    public static final String POSTGRESQL_JDBC_DRIVER = "org.postgresql.Driver";
37
    
38
    public static final boolean USE_CONNECTIONS_POOL = true;
39
    
40
    public static String getConnectionURL(PostgreSQLConnectionParameters params) {
41
        return getConnectionURL(
42
            params.getHost(),
43
            params.getPort(),
44
            params.getDBName()
45
        );
46
    }
47
    
48
    public static String getConnectionURL(String host, Integer port, String db) {
49
        if( StringUtils.isEmpty(host) ) {
50
            throw new IllegalArgumentException("Parameter 'host' can't be null.");
51
        }
52
        String connectionURL = "jdbc:postgresql://" + host;
53
        if (port != null) {
54
            connectionURL = connectionURL + ":" + port;
55
        }
56
        connectionURL = connectionURL + "/" + db;
57
        LOGGER.debug("connectionURL: {}", connectionURL);
58
        return connectionURL;
59
    }
60

  
61
    private static class PostgreSQLConnectionProvider implements Disposable, ConnectionProvider {
62

  
63
        private static boolean needRegisterDriver = true;
64

  
65
        private BasicDataSource dataSource = null;
66

  
67
        private PostgreSQLConnectionParameters connectionParameters;
68

  
69
        public PostgreSQLConnectionProvider(PostgreSQLConnectionParameters connectionParameters) {
70
            this.connectionParameters = connectionParameters;
71
        }
72

  
73
        @Override
74
        public Connection getConnection() throws SQLException {
75
            
76
            Connection conn;
77
            if( USE_CONNECTIONS_POOL ) {
78
                if (this.dataSource == null) {
79
                    this.dataSource = this.createDataSource();               
80
                }
81
                if( LOGGER.isDebugEnabled() ) {
82
                    LOGGER.debug("getConnection:\n" + getStatusInformation());
83
                }
84
                try {
85
                    conn = this.dataSource.getConnection();
86
                } catch(Throwable ex) {
87
                    LOGGER.debug("Error getting connection from pool.",ex);
88
                    throw ex;
89
                }
90
                try {
91
                    conn.setNetworkTimeout(null, this.connectionParameters.getNetworkTimeout());
92
                } catch(Throwable ex) {
93
                    LOGGER.warn("Error setting the network timeout.",ex);
94
                }
95
                if( LOGGER.isDebugEnabled() ) {
96
                    LOGGER.debug("Created connection: {}\n  NumActive: {}\n  NumIdle: {}",
97
                        new Object[] {
98
                            conn.hashCode(), 
99
                            this.dataSource.getNumActive(),
100
                            this.dataSource.getNumIdle()
101
                        }
102
                    );
103
                }
104
            } else {
105
                try {
106
                    conn = DriverManager.getConnection(
107
                        connectionParameters.getUrl(), 
108
                        connectionParameters.getUser(), 
109
                        connectionParameters.getPassword()
110
                    );
111
                } catch(Throwable th) {
112
                    throw th;
113
                }
114
                if( LOGGER.isDebugEnabled() ) {
115
                    LOGGER.debug("Created not polled connection: {}",
116
                        new Object[] {
117
                            conn.hashCode()
118
                        }
119
                    );
120
                }
121
            }
122
            LOGGER.debug("PostgreSQL JDBC Driver: "+DriverInfo.DRIVER_VERSION);
123
            return conn;
124
        }
125
        
126
        public String getStatusInformation() {
127
            StringBuilder builder = new StringBuilder();
128
            if( this.dataSource==null ) {
129
                builder.append("Not poolled connection:\n");
130
                builder.append("  Connection URL: '").append(this.connectionParameters.getUrl()).append("'\n");
131
            } else {
132
                builder.append("BasicDataSource pool status:\n");
133
                builder.append("  Connection URL: '").append(this.dataSource.getUrl()).append("'\n");
134
                if( this.dataSource.getInitialSize()>0 ) {
135
                    builder.append("  InitialSize: ").append(this.dataSource.getInitialSize()).append(" (The initial number of connections that are created when the pool is started)\n");
136
                }
137
                if( this.dataSource.isPoolPreparedStatements() ) {
138
                    builder.append("  PoolPreparedStatements: ").append(this.dataSource.isPoolPreparedStatements()).append("\n");
139
                    builder.append("  MaxOpenPreparedStatements: ").append(this.dataSource.getMaxOpenPreparedStatements()).append(" (The maximum number of open statements that can be allocated from the statement pool at the same time, or non-positive for no limit)\n");
140
                }
141
                builder.append("  MaxTotal: ").append(this.dataSource.getMaxTotal()).append(" (The maximum number of active connections that can be allocated from this pool at the same time)\n");
142
                builder.append("  MaxIdle: ").append(this.dataSource.getMaxIdle()).append(" (The maximum number of connections that can remain idle in the pool)\n");
143
                builder.append("  NumActive:").append(this.dataSource.getNumActive()).append(" (the current number of active connections)\n");
144
                builder.append("  NumIdle:").append(this.dataSource.getNumIdle()).append(" (the current number of idle connections)\n");
145
            }
146
            return builder.toString();
147
        }
148

  
149
        private BasicDataSource createDataSource() throws SQLException {
150
            if (!this.isRegistered()) {
151
                this.registerDriver();
152
            }
153
            PostgreSQLConnectionParameters params = connectionParameters;
154

  
155
            BasicDataSource ds = new BasicDataSource();
156
            ds.setMaxIdle(params.getMaxIdle());
157
            ds.setDriverClassName(params.getJDBCDriverClassName());
158
            if( params.getUseSSL() ) {
159
                String s = BooleanUtils.toStringTrueFalse(params.getUseSSL());
160
                ds.addConnectionProperty("ssl", s );
161
            }
162
            if( !StringUtils.isEmpty(params.getUser()) ) {
163
                ds.setUsername(params.getUser());
164
            }
165
            if( !StringUtils.isEmpty(params.getPassword()) ) {
166
                ds.setPassword(params.getPassword());
167
            }
168
            ds.setUrl(params.getUrl());
169
            
170
            ds.setMinEvictableIdleTimeMillis(20*1000);
171
            ds.setTimeBetweenEvictionRunsMillis(20*1000);
172
            ds.setMinIdle(0);
173
            
174
            ds.setMaxWaitMillis(60L * 1000);
175
            return ds;
176
        }
177

  
178
        private boolean isRegistered() {
179
            return needRegisterDriver;
180
        }
181

  
182
        @Override
183
        public void registerDriver() throws SQLException {
184
            String className = this.connectionParameters.getJDBCDriverClassName();
185
            if (className == null) {
186
                return;
187
            }
188
            try {
189
                Class theClass = Class.forName(className);
190
                if (theClass == null) {
191
                    throw new JDBCDriverClassNotFoundException(PostgreSQLLibrary.NAME, className);
192
                }
193
            } catch (Exception e) {
194
                throw new SQLException("Can't register JDBC driver '" + className + "'.", e);
195
            }
196
            needRegisterDriver = false;
197
        }
198

  
199
        @Override
200
        public void dispose() {
201
            if( this.dataSource!=null ) {
202
                try {
203
                    this.dataSource.close();
204
                } catch (SQLException ex) {
205
                    LOGGER.warn("Can't close BasicDataSource", ex);
206
                }
207
                this.dataSource = null;
208
            }
209
            this.connectionParameters = null;
210
        }
211

  
212
        @Override
213
        public String getStatus() {
214
            if( dataSource==null ) {
215
                return "Not polled";
216
            }
217
            StringBuilder builder = new StringBuilder();
218
            builder.append("Pool: ");
219
            builder.append(JDBCUtils.getHexId(dataSource));
220
            builder.append(" Actives: ");
221
            builder.append(dataSource.getNumActive());
222
            builder.append("/");
223
            builder.append(dataSource.getMaxTotal()); //.getMaxActive());
224
            builder.append(" idle: ");
225
            builder.append(dataSource.getNumIdle());
226
            builder.append("/");
227
            builder.append(dataSource.getMinIdle());
228
            builder.append(":");
229
            builder.append(dataSource.getMaxIdle());
230
            return builder.toString();
231
        }
232

  
233
    }
234

  
235
    private ConnectionProvider connectionProvider = null;
236
   
237
    /**
238
     * Constructor for use only for testing purposes.
239
     * 
240
     * @param connectionParameters
241
     * @param connectionProvider
242
     */
243
    public PostgreSQLHelper(PostgreSQLConnectionParameters connectionParameters, ConnectionProvider connectionProvider) { 
244
        super(connectionParameters);
245
        this.srssolver = new SRSSolverDumb(this);
246
        this.connectionProvider = connectionProvider;
247
    }
248
  
249

  
250

  
251
    public PostgreSQLHelper(JDBCConnectionParameters connectionParameters) {
252
        super(connectionParameters);
253
        this.srssolver = new SRSSolverBase(this);
254
    }
255

  
256
    @Override
257
    protected void doDispose() throws BaseException {
258
        if( this.connectionProvider!=null ) {
259
            this.connectionProvider.dispose();
260
            this.connectionProvider = null;
261
        }
262
        super.doDispose(); 
263
    }
264

  
265
    @Override
266
    public Connection getConnection() throws AccessResourceException {
267
        try {
268
            if (this.connectionProvider == null) {
269
              if( this.getConnectionParameters()==null ) {
270
                return null;
271
              }
272
              this.connectionProvider = new PostgreSQLConnectionProvider(this.getConnectionParameters());
273
            }
274
            return this.connectionProvider.getConnection();
275
        } catch (SQLException ex) {
276
            throw new AccessResourceException(PostgreSQLLibrary.NAME, ex);
277
        }
278
    }
279

  
280
    @Override
281
    public void closeConnection(Connection connection) {
282
        if (connection != null) { // In test ???
283
            LOGGER.debug("[" + JDBCUtils.getConnId(connection) + "] closeConnection " + this.connectionProvider.getStatus());
284
        }
285
        super.closeConnection(connection);
286
    }
287
    
288
    @Override
289
    public PostgreSQLConnectionParameters getConnectionParameters() {
290
        return (PostgreSQLConnectionParameters) super.getConnectionParameters();
291
    }
292
    
293
    @Override
294
    public String getConnectionURL() {
295
        return getConnectionURL(this.getConnectionParameters());
296
    }
297

  
298
    @Override
299
    protected String getResourceType() {
300
        return PostgreSQLLibrary.NAME;
301
    }
302

  
303
    @Override
304
    public String getProviderName() {
305
        return PostgreSQLLibrary.NAME;
306
    }
307

  
308
    @Override
309
    public JDBCSQLBuilderBase createSQLBuilder() {
310
        return new PostgreSQLBuilder(this);
311
    }
312
    
313
    @Override
314
    public OperationsFactory getOperations() {
315
        if (this.operationsFactory == null) {
316
            this.operationsFactory = new PostgreSQLOperationsFactory(this);
317
        }
318
        return operationsFactory;
319
    }
320

  
321
    @Override
322
    public GeometrySupportType getGeometrySupportType() {
323
        return GeometrySupportType.EWKB;
324
    }
325

  
326
    @Override
327
    public boolean hasSpatialFunctions() {
328
        return true;
329
    }
330

  
331
    @Override
332
    public boolean canWriteGeometry(int geometryType, int geometrySubtype) {
333
        return true;
334
    }
335

  
336
    @Override
337
    public String getQuoteForIdentifiers() {
338
        return "\"";
339
    }
340

  
341
    @Override
342
    public boolean allowAutomaticValues() {
343
        return true;
344
    }
345

  
346
    @Override
347
    public boolean supportOffsetInSelect() {
348
        return true;
349
    }
350

  
351
    @Override
352
    public String getQuoteForStrings() {
353
        return "'";
354
    }
355
    
356
    @Override
357
    public String getSourceId(JDBCStoreParameters parameters) {
358
        return parameters.getDBName() + "." + 
359
               parameters.getSchema()+ "." + 
360
               parameters.getTable();
361
    }
362

  
363
    @Override
364
    public JDBCNewStoreParameters createNewStoreParameters() {
365
        return new PostgreSQLNewStoreParameters();
366
    }
367

  
368
    @Override
369
    public JDBCStoreParameters createOpenStoreParameters() {
370
        return new PostgreSQLStoreParameters();
371
    }
372

  
373
    @Override
374
    public JDBCServerExplorerParameters createServerExplorerParameters() {
375
        return new PostgreSQLServerExplorerParameters();
376
    }
377
}
tags/org.gvsig.postgresql-2.0.202/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/PostgreSQLServerExplorerFactory.java
1

  
2
package org.gvsig.postgresql.dal;
3

  
4
import org.apache.commons.lang3.StringUtils;
5
import org.gvsig.fmap.dal.DataServerExplorerParameters;
6
import org.gvsig.fmap.dal.exception.InitializeException;
7
import org.gvsig.fmap.dal.spi.DataServerExplorerProviderServices;
8
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
9
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters;
10
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
11
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
12
import org.gvsig.fmap.dal.store.jdbc2.JDBCServerExplorer;
13
import org.gvsig.fmap.dal.store.jdbc2.impl.JDBCServerExplorerFactory;
14

  
15

  
16
public class PostgreSQLServerExplorerFactory extends JDBCServerExplorerFactory {
17

  
18
    private static final String NAME = PostgreSQLLibrary.NAME;
19
    
20
    public PostgreSQLServerExplorerFactory() {
21
        super(
22
            NAME,
23
            "PostgreSQL Server"
24
        );
25
    }
26

  
27
    public PostgreSQLServerExplorerFactory(String name) {
28
        // Cuando se instancia la factoria con un "name" que no es el de por
29
        // defecto, es para declarar "alias" para el ServerExplorer, normalmente
30
        // para mantener compatibilidad con versiones anteriores. 
31
        // Marcaremos la factoria como "hidden" para que no aparezca
32
        // en el interface de usuario.
33
        super(
34
            name,
35
            "PostgreSQL Server (for compatibility)",
36
            true
37
        );
38
    }
39

  
40
    @Override
41
    public JDBCServerExplorer create(
42
            DataServerExplorerParameters parameters, 
43
            DataServerExplorerProviderServices providerServices
44
        ) throws InitializeException {
45
        // Esto seria para convertir los parametros de gvSIG 2.3 a 2.4.
46
//        if( !StringUtils.equalsIgnoreCase(NAME, (CharSequence) parameters.getDynValue(DataStoreProviderServices.PROVIDER_PARAMTER_NAME)) ) {
47
//            parameters.setDynValue(DataStoreProviderServices.PROVIDER_PARAMTER_NAME, NAME);
48
//        }
49
        JDBCHelper helper = new PostgreSQLHelper((JDBCConnectionParameters) parameters);
50
        JDBCServerExplorer server = helper.createServerExplorer(
51
                (JDBCServerExplorerParameters) parameters, 
52
                providerServices
53
        );
54
        return server;
55
    }
56
        
57

  
58
    @Override
59
    public JDBCServerExplorerParameters createParameters() {
60
        JDBCServerExplorerParameters params = new PostgreSQLServerExplorerParameters();
61
        return params;    
62
    }
63
    
64
}
tags/org.gvsig.postgresql-2.0.202/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/PostgreSQLStoreProviderFactory.java
1
package org.gvsig.postgresql.dal;
2

  
3
import java.util.Arrays;
4
import java.util.Collections;
5
import java.util.HashSet;
6
import java.util.Set;
7
import java.util.function.Function;
8
import org.gvsig.fmap.dal.DataParameters;
9
import static org.gvsig.fmap.dal.DataStoreProviderFactory.NO;
10
import static org.gvsig.fmap.dal.DataStoreProviderFactory.UNKNOWN;
11
import static org.gvsig.fmap.dal.DataStoreProviderFactory.YES;
12
import org.gvsig.fmap.dal.exception.InitializeException;
13
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
14
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters;
15
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
16
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
17
import org.gvsig.fmap.dal.store.jdbc2.JDBCStoreProvider;
18
import org.gvsig.fmap.dal.store.jdbc2.impl.JDBCStoreProviderFactory;
19

  
20
public class PostgreSQLStoreProviderFactory extends JDBCStoreProviderFactory {
21

  
22
    private static final Set<String> ALLOWED_FUNCTIONS = new HashSet<>(
23
            Arrays.asList(new String[]{
24
        "COUNT",
25
        "SUM",
26
        "MIN",
27
        "MAX"
28
    }
29
            )
30
    );
31
    private static final Set<String> DENIED_FUNCTIONS = Collections.EMPTY_SET;
32

  
33
    public PostgreSQLStoreProviderFactory() {
34
        super(
35
                PostgreSQLLibrary.NAME,
36
                "PostgreSQL store"
37
        );
38
    }
39

  
40
    @Override
41
    public JDBCStoreProvider createProvider(
42
            DataParameters parameters,
43
            DataStoreProviderServices providerServices
44
    ) throws InitializeException {
45
        JDBCHelper helper = new PostgreSQLHelper((JDBCConnectionParameters) parameters);
46
        JDBCStoreProvider provider = helper.createProvider(
47
                (JDBCStoreParameters) parameters,
48
                providerServices
49
        );
50
        return provider;
51
    }
52

  
53
    @Override
54
    public JDBCStoreParameters createParameters() {
55
        JDBCStoreParameters params = new PostgreSQLStoreParameters();
56
        return params;
57
    }
58

  
59
    @Override
60
    public Function<String, Integer> allowFunction() {
61
        return (Function<String, Integer>) (String name) -> {
62
            if (ALLOWED_FUNCTIONS.contains(name)) {
63
                return YES;
64
            }
65
            if (DENIED_FUNCTIONS.contains(name)) {
66
                return NO;
67
            }
68
            return UNKNOWN;
69
        };
70
    }
71

  
72
    @Override
73
    public int allowGroupBy() {
74
        return YES;
75
    }
76

  
77
    @Override
78
    public int hasVectorialSupport() {
79
        return YES;
80
    }
81

  
82
    @Override
83
    public int hasRasterSupport() {
84
        return NO;
85
    }
86

  
87
    @Override
88
    public int hasTabularSupport() {
89
        return YES;
90
    }
91

  
92
    @Override
93
    public int hasSQLSupport() {
94
        return YES;
95
    }
96
}
tags/org.gvsig.postgresql-2.0.202/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/operations/PostgreSQLFetchFeatureTypeOperation.java
1

  
2
package org.gvsig.postgresql.dal.operations;
3

  
4
import java.sql.Connection;
5
import java.sql.ResultSet;
6
import java.sql.ResultSetMetaData;
7
import java.sql.SQLException;
8
import java.sql.Statement;
9
import java.util.HashMap;
10
import java.util.List;
11
import java.util.Map;
12
import org.apache.commons.lang3.StringUtils;
13
import org.cresques.cts.IProjection;
14
import org.gvsig.expressionevaluator.ExpressionBuilder;
15
import org.gvsig.fmap.dal.DataTypes;
16
import org.gvsig.fmap.dal.exception.DataException;
17
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
18
import org.gvsig.fmap.dal.feature.EditableFeatureType;
19
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
20
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
21
import org.gvsig.fmap.dal.store.jdbc2.OperationsFactory.TableReference;
22
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
23
import org.gvsig.fmap.dal.store.jdbc2.spi.SRSSolver;
24
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.FetchFeatureTypeOperation;
25
import org.gvsig.fmap.geom.Geometry;
26
import org.gvsig.fmap.geom.GeometryLocator;
27
import org.gvsig.fmap.geom.GeometryManager;
28
import org.gvsig.fmap.geom.type.GeometryType;
29
import org.gvsig.postgresql.dal.PostgreSQLBuilder;
30

  
31
@SuppressWarnings("UseSpecificCatch")
32
public class PostgreSQLFetchFeatureTypeOperation extends FetchFeatureTypeOperation {
33

  
34
    private static Map<String,GeometryType>databaseGeometryTypes = null;
35
    
36
    public PostgreSQLFetchFeatureTypeOperation(
37
            JDBCHelper helper
38
        ) {
39
        super(helper);
40
    }
41

  
42
    private GeometryType getGT(
43
            GeometryManager manager, 
44
            int type, 
45
            int subtype
46
        ) {
47
        try {
48
            return manager.getGeometryType(type, subtype);
49
        } catch (Exception ex) {
50
            return null;
51
        }
52
    }
53
    
54
    public PostgreSQLFetchFeatureTypeOperation(
55
            JDBCHelper helper,
56
            EditableFeatureType featureType,
57
            TableReference table,
58
            List<String> primaryKeys,
59
            String defaultGeometryColumn,
60
            IProjection crs,
61
            int geometryType,
62
            int geometrySubtype
63
    ) {
64
        super(helper, featureType, table, primaryKeys, defaultGeometryColumn, crs, geometryType, geometrySubtype);
65
    }
66
    
67

  
68
    @Override
69
    public void fetch(Connection conn) throws DataException {
70
        super.fetch(conn);
71
    }
72

  
73
    @Override
74
    protected int getDataTypeFromMetadata(
75
            ResultSetMetaData rsMetadata,
76
            int colIndex
77
        ) throws SQLException {
78

  
79
        return super.getDataTypeFromMetadata(rsMetadata, colIndex);
80
    }
81
    
82
    @Override
83
    public String getSQLToRetrievePrimaryKeysFromInformationSchema() throws SQLException {
84
        PostgreSQLBuilder sqlbuilder = (PostgreSQLBuilder) this.createSQLBuilder();
85
        ExpressionBuilder expbuilder = sqlbuilder.expression();
86
        
87
        String column_COLUMN_NAME = "column_name";
88
        String column_CONSTRAINT_TYPE = "constraint_type";
89
        
90
        if( sqlbuilder.getDatabaseVersion().getMajor()<10 ) {
91
            column_COLUMN_NAME = "COLUMN_NAME";
92
            column_CONSTRAINT_TYPE = "CONSTRAINT_TYPE";
93
        }
94
        sqlbuilder.select().column().name(column_COLUMN_NAME);
95
        sqlbuilder.select().column().name(column_CONSTRAINT_TYPE);
96
        sqlbuilder.select().from().custom(
97
                "INFORMATION_SCHEMA.table_constraints t_cons "
98
                + "inner join INFORMATION_SCHEMA.key_column_usage c on "
99
                + "c.constraint_catalog = t_cons.constraint_catalog and "
100
                + "c.table_schema = t_cons.table_schema and "
101
                + "c.table_name = t_cons.table_name and "
102
                + "c.constraint_name = t_cons.constraint_name "
103
        );
104
        sqlbuilder.select().where().set(
105
                expbuilder.like(
106
                        expbuilder.custom("c.TABLE_NAME"), 
107
                        expbuilder.constant(table.getTable())
108
                )
109
        );
110
        if (table.hasSchema()) {
111
            sqlbuilder.select().where().and(
112
                    expbuilder.like(
113
                            expbuilder.custom("c.TABLE_SCHEMA"),
114
                            expbuilder.constant(table.getSchema())
115
                    )
116
            );
117
        }
118
//        if (catalog != null) {
119
//            sqlbuilder.select().where().and(
120
//                    expbuilder.like(
121
//                            expbuilder.custom("c.CONSTRAINT_CATALOG"),
122
//                            expbuilder.constant(catalog)
123
//                    )
124
//            );
125
//        }
126
        sqlbuilder.select().where().and(
127
                expbuilder.eq(
128
                        expbuilder.column(column_CONSTRAINT_TYPE),
129
                        expbuilder.constant("PRIMARY KEY")
130
                )
131
        );
132
        return sqlbuilder.toString();
133
    }
134
        
135
    @Override
136
    protected void fetchGeometryTypeAndSRS(
137
            EditableFeatureAttributeDescriptor attr,
138
            ResultSetMetaData rsMetadata,
139
            int colIndex
140
        ) {
141
        if( attr.getType()!=DataTypes.GEOMETRY ) {
142
            return;
143
        }
144
        try {
145
            JDBCSQLBuilderBase sqlbuilder = this.createSQLBuilder();
146
            ExpressionBuilder expbuilder = sqlbuilder.expression();
147
            
148
            sqlbuilder.select().column().name("f_table_catalog");
149
            sqlbuilder.select().column().name("f_table_schema");
150
            sqlbuilder.select().column().name("f_table_name");
151
            sqlbuilder.select().column().name("f_geometry_column");
152
            sqlbuilder.select().column().name("coord_dimension");
153
            sqlbuilder.select().column().name("srid");
154
            sqlbuilder.select().column().name("type");
155
            sqlbuilder.select().where().set(
156
                    expbuilder.eq(
157
                            expbuilder.column("f_table_name"),
158
                            expbuilder.constant(this.getTable().getTable())
159
                    )
160
            );                
161
            sqlbuilder.select().where().and(
162
                    expbuilder.eq(
163
                            expbuilder.column("f_geometry_column"),
164
                            expbuilder.constant(attr.getName())
165
                    )
166
            );         
167
            sqlbuilder.select().from().table().name("geometry_columns");
168
            Statement st = null;
169
            ResultSet rs = null;
170
            
171
            Integer srsid = null;
172
            String geometryTypeName = null;
173
            try {
174
                st = this.getConnection().createStatement();
175
                rs = JDBCUtils.executeQuery(st, sqlbuilder.toString());
176
                if (rs.next()) {
177
                    srsid = rs.getInt("srid");
178
                    geometryTypeName = rs.getString("type");
179
                }
180
            } finally {
181
                JDBCUtils.closeQuietly(rs);
182
                JDBCUtils.closeQuietly(st);
183
            }
184
            if( !StringUtils.isEmpty(geometryTypeName) ) {
185
                GeometryType gt = getGeometryTypeFromDatabaseTypeName(geometryTypeName);
186
                attr.setGeometryType(gt);
187
            }
188
            if( srsid!=null ) {
189
                SRSSolver srssolver = this.helper.getSRSSolver();
190
                attr.setSRS(srssolver.getProjection(this.getConnection(),srsid));
191
            }
192
        } catch (Exception ex) {
193
            LOGGER.debug("Can't get geometry type and srs from column '"+attr.getName()+"'.",ex);
194
        }
195
    }
196

  
197
    private GeometryType getGeometryTypeFromDatabaseTypeName(String typeName) {
198
        if( databaseGeometryTypes==null ) {
199
            GeometryManager manager = GeometryLocator.getGeometryManager();
200
            databaseGeometryTypes = new HashMap<>();
201
            databaseGeometryTypes.put("POINT", getGT(manager, Geometry.TYPES.POINT,Geometry.SUBTYPES.GEOM2D));
202
            databaseGeometryTypes.put("POINTZ", getGT(manager, Geometry.TYPES.POINT,Geometry.SUBTYPES.GEOM3D));
203
            databaseGeometryTypes.put("POINTM", getGT(manager, Geometry.TYPES.POINT,Geometry.SUBTYPES.GEOM2DM));
204
            databaseGeometryTypes.put("POINTZM", getGT(manager, Geometry.TYPES.POINT,Geometry.SUBTYPES.GEOM3DM));
205
            
206
            databaseGeometryTypes.put("LINESTRING", getGT(manager, Geometry.TYPES.LINE,Geometry.SUBTYPES.GEOM2D));
207
            databaseGeometryTypes.put("LINESTRINGZ", getGT(manager, Geometry.TYPES.LINE,Geometry.SUBTYPES.GEOM3D));
208
            databaseGeometryTypes.put("LINESTRINGM", getGT(manager, Geometry.TYPES.LINE,Geometry.SUBTYPES.GEOM2DM));
209
            databaseGeometryTypes.put("LINESTRINGZM", getGT(manager, Geometry.TYPES.LINE,Geometry.SUBTYPES.GEOM3DM));
210
            
211
            databaseGeometryTypes.put("POLYGON", getGT(manager, Geometry.TYPES.POLYGON,Geometry.SUBTYPES.GEOM2D));
212
            databaseGeometryTypes.put("POLYGONZ", getGT(manager, Geometry.TYPES.POLYGON,Geometry.SUBTYPES.GEOM3D));
213
            databaseGeometryTypes.put("POLYGONM", getGT(manager, Geometry.TYPES.POLYGON,Geometry.SUBTYPES.GEOM2DM));
214
            databaseGeometryTypes.put("POLYGONZM", getGT(manager, Geometry.TYPES.POLYGON,Geometry.SUBTYPES.GEOM3DM));
215

  
216
            databaseGeometryTypes.put("MULTIPOINT", getGT(manager, Geometry.TYPES.MULTIPOINT,Geometry.SUBTYPES.GEOM2D));
217
            databaseGeometryTypes.put("MULTIPOINTZ", getGT(manager, Geometry.TYPES.MULTIPOINT,Geometry.SUBTYPES.GEOM3D));
218
            databaseGeometryTypes.put("MULTIPOINTM", getGT(manager, Geometry.TYPES.MULTIPOINT,Geometry.SUBTYPES.GEOM2DM));
219
            databaseGeometryTypes.put("MULTIPOINTZM", getGT(manager, Geometry.TYPES.MULTIPOINT,Geometry.SUBTYPES.GEOM3DM));
220

  
221
            databaseGeometryTypes.put("MULTILINESTRING", getGT(manager, Geometry.TYPES.MULTILINE,Geometry.SUBTYPES.GEOM2D));
222
            databaseGeometryTypes.put("MULTILINESTRINGZ", getGT(manager, Geometry.TYPES.MULTILINE,Geometry.SUBTYPES.GEOM3D));
223
            databaseGeometryTypes.put("MULTILINESTRINGM", getGT(manager, Geometry.TYPES.MULTILINE,Geometry.SUBTYPES.GEOM2DM));
224
            databaseGeometryTypes.put("MULTILINESTRINGZM", getGT(manager, Geometry.TYPES.MULTILINE,Geometry.SUBTYPES.GEOM3DM));
225

  
226
            databaseGeometryTypes.put("MULTIPOLYGON", getGT(manager, Geometry.TYPES.MULTIPOLYGON,Geometry.SUBTYPES.GEOM2D));
227
            databaseGeometryTypes.put("MULTIPOLYGONZ", getGT(manager, Geometry.TYPES.MULTIPOLYGON,Geometry.SUBTYPES.GEOM3D));
228
            databaseGeometryTypes.put("MULTIPOLYGONM", getGT(manager, Geometry.TYPES.MULTIPOLYGON,Geometry.SUBTYPES.GEOM2DM));
229
            databaseGeometryTypes.put("MULTIPOLYGONZM", getGT(manager, Geometry.TYPES.MULTIPOLYGON,Geometry.SUBTYPES.GEOM3DM));
230

  
231
            databaseGeometryTypes.put("GEOMETRY", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM2D));
232
            databaseGeometryTypes.put("GEOMETRYZ", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM3D));
233
            databaseGeometryTypes.put("GEOMETRYM", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM2DM));
234
            databaseGeometryTypes.put("GEOMETRYZM", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM3DM));
235
        }
236
        return databaseGeometryTypes.get(typeName);
237
    }
238
    
239
}
tags/org.gvsig.postgresql-2.0.202/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/operations/PostgreSQLOperationsFactory.java
1

  
2
package org.gvsig.postgresql.dal.operations;
3

  
4
import java.util.List;
5
import org.cresques.cts.IProjection;
6
import org.gvsig.fmap.dal.feature.EditableFeatureType;
7
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
8
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.FetchFeatureTypeOperation;
9
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.OperationsFactoryBase;
10

  
11

  
12
public class PostgreSQLOperationsFactory extends OperationsFactoryBase {
13
    
14
    public PostgreSQLOperationsFactory(JDBCHelper helper) {
15
        super(helper);
16
    }
17

  
18
    @Override
19
    public FetchFeatureTypeOperation createFetchFeatureType(EditableFeatureType type, TableReference table, List<String> primaryKeys, String defaultGeometryField, IProjection crs) {
20
        return new PostgreSQLFetchFeatureTypeOperation(
21
                helper, type, table, primaryKeys, 
22
                defaultGeometryField, crs, -1, -1
23
        );
24
    }  
25

  
26
    @Override
27
    public FetchFeatureTypeOperation createFetchFeatureType(EditableFeatureType type, TableReference table, List<String> primaryKeys, String defaultGeometryField, IProjection crs, int geometryType, int geometrySubtype) {
28
        return new PostgreSQLFetchFeatureTypeOperation(
29
                helper, type, table, primaryKeys, 
30
                defaultGeometryField, crs, geometryType, geometrySubtype
31
        );
32
    }  
33

  
34
}
tags/org.gvsig.postgresql-2.0.202/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/PostgreSQLStoreParameters.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.postgresql.dal;
23

  
24
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
25
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
26

  
27
public class PostgreSQLStoreParameters extends JDBCStoreParameters implements PostgreSQLConnectionParameters {
28

  
29
    private final PostgreSQLConnectionParametersHelper helper;
30
    
31
    public PostgreSQLStoreParameters() {
32
        super(
33
                PostgreSQLLibrary.NAME + "StoreParameters",
34
                PostgreSQLLibrary.NAME
35
        );
36
        this.helper = new PostgreSQLConnectionParametersHelper(this);
37
    }
38

  
39
    @Override
40
    public String getUrl() {
41
        return this.helper.getUrl();
42
    }
43
    
44
    @Override
45
    public void validate() throws ValidateDataParametersException {
46
        this.helper.validate();
47
        super.validate();
48
    }
49

  
50
    @Override
51
    public boolean getUseSSL() {
52
        return this.helper.getUseSSL();
53
    }
54

  
55
    @Override
56
    public int getMaxIdle() {
57
        return this.helper.getMaxIdle();
58
    }
59

  
60
    public void setUseSSL(boolean v) {
61
        this.helper.setUseSSL(v);
62
    }
63

  
64
    @Override
65
    public int getNetworkTimeout() {
66
        return this.helper.getNetworkTimeout();
67
    }
68
    
69
}
tags/org.gvsig.postgresql-2.0.202/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/PostgreSQLConnectionParameters.java
1
package org.gvsig.postgresql.dal;
2

  
3
import org.gvsig.fmap.dal.resource.db.DBParameters;
4
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters;
5

  
6
public interface PostgreSQLConnectionParameters extends JDBCConnectionParameters, DBParameters {
7

  
8
    public static final String USESSL_PARAMTER_NAME = "UseSSL";
9
    public static final String MAXIDLE_PARAMTER_NAME = "maxIdle";
10
    public static final String NETWORK_TIMEOUT = "networkTimeout";
11

  
12
    public boolean getUseSSL();
13

  
14
    public int getMaxIdle();
15

  
16
    public int getNetworkTimeout();
17
}
tags/org.gvsig.postgresql-2.0.202/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/PostgreSQLConnectionParametersHelper.java
1

  
2
package org.gvsig.postgresql.dal;
3

  
4
import org.apache.commons.lang3.StringUtils;
5
import org.gvsig.fmap.dal.DataParameters;
6
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
7
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters;
8

  
9

  
10
public class PostgreSQLConnectionParametersHelper {
11

  
12
    private final JDBCConnectionParameters parameters;
13
    
14
    public PostgreSQLConnectionParametersHelper(JDBCConnectionParameters parameters) {
15
        this.parameters = parameters;
16
    }
17

  
18
    public String getUrl() {
19
        String url = (String) this.getDynValue(JDBCConnectionParameters.URL_PARAMTER_NAME);
20
        if( StringUtils.isEmpty(url) ) {
21
            url = PostgreSQLHelper.getConnectionURL((PostgreSQLConnectionParameters) this.parameters);
22
            this.setDynValue(JDBCConnectionParameters.URL_PARAMTER_NAME,url);
23
        }
24
        return url;
25
    }
26
    
27
    public void validate() throws ValidateDataParametersException {
28
        if (this.getDynValue(JDBCConnectionParameters.JDBC_DRIVER_CLASS_PARAMTER_NAME) == null) {
29
            this.setDynValue(
30
                JDBCConnectionParameters.JDBC_DRIVER_CLASS_PARAMTER_NAME,
31
                PostgreSQLHelper.POSTGRESQL_JDBC_DRIVER
32
            );
33
        }
34
        if( this.getDynValue(JDBCConnectionParameters.PORT_PARAMTER_NAME)==null ) {
35
            this.setDynValue(JDBCConnectionParameters.PORT_PARAMTER_NAME, 5432);
36
        }
37
		if ( StringUtils.isEmpty((CharSequence) this.getDynValue(JDBCConnectionParameters.URL_PARAMTER_NAME))) {
38
            String url = PostgreSQLHelper.getConnectionURL(
39
                parameters.getHost(),
40
                parameters.getPort(),
41
                parameters.getDBName()
42
            );
43
            this.setDynValue(JDBCConnectionParameters.URL_PARAMTER_NAME, url);
44
		}
45
    }
46

  
47
    private Object getDynValue(String name) {
48
        return ((DataParameters)this.parameters).getDynValue(name);
49
    }
50
    
51
    private void setDynValue(String name, Object value) {
52
        ((DataParameters)this.parameters).setDynValue(name,value);
53
    }
54
    
55
    public int getMaxIdle() {
56
        return (int) this.getDynValue(PostgreSQLConnectionParameters.MAXIDLE_PARAMTER_NAME);
57
    }
58

  
59
    public boolean getUseSSL() {
60
        return (boolean) this.getDynValue(PostgreSQLConnectionParameters.USESSL_PARAMTER_NAME);
61
    }
62

  
63
    public void setUseSSL(boolean v) {
64
        this.setDynValue(PostgreSQLConnectionParameters.USESSL_PARAMTER_NAME, v);
65
    }
66

  
67
    public int getNetworkTimeout() {
68
        return (int) this.getDynValue(PostgreSQLConnectionParameters.NETWORK_TIMEOUT);
69
    }
70

  
71
}
tags/org.gvsig.postgresql-2.0.202/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/PostgreSQLLibrary.java
1

  
2
package org.gvsig.postgresql.dal;
3

  
4
import org.gvsig.fmap.dal.DALLibrary;
5
import org.gvsig.fmap.dal.DALLocator;
6
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
7
import org.gvsig.fmap.dal.store.db.DBHelper;
8
import org.gvsig.fmap.dal.store.jdbc2.JDBCLibrary;
9
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCStoreProviderBase;
10
import org.gvsig.json.Json;
11
import org.gvsig.metadata.exceptions.MetadataException;
12
import org.gvsig.tools.library.AbstractLibrary;
13
import org.gvsig.tools.library.LibraryException;
14

  
15

  
16
public class PostgreSQLLibrary extends AbstractLibrary {
17

  
18
    public static final String NAME = "PostgreSQL";
19

  
20
    @Override
21
    public void doRegistration() {
22
        registerAsServiceOf(DALLibrary.class);
23
        require(JDBCLibrary.class);
24
    }
25

  
26
    @Override
27
    protected void doInitialize() throws LibraryException {
28
    }
29

  
30
    @Override
31
    protected void doPostInitialize() throws LibraryException {
32
        LibraryException ex = null;
33

  
34
        DataManagerProviderServices dataman = 
35
                (DataManagerProviderServices) DALLocator.getDataManager();
36

  
37
        try {
38
            Class.forName(PostgreSQLHelper.POSTGRESQL_JDBC_DRIVER);
39
        } catch(Throwable th) {
40
            PostgreSQLHelper.LOGGER.warn("Can't load PostgreSQL JDBC Driver.",th);
41
        }
42
        
43
        DBHelper.registerParametersDefinition(
44
                NAME + "StoreParameters",
45
                PostgreSQLStoreParameters.class,
46
                dataman.getResourceAsStream(this, NAME + "Parameters.xml")
47
        );
48
        DBHelper.registerParametersDefinition(
49
                NAME + "NewStoreParameters",
50
                PostgreSQLNewStoreParameters.class,
51
                dataman.getResourceAsStream(this, NAME + "Parameters.xml")
52
        );
53
        DBHelper.registerParametersDefinition(
54
                NAME + "ServerExplorerParameters",
55
                PostgreSQLServerExplorerParameters.class,
56
                dataman.getResourceAsStream(this, NAME + "Parameters.xml")
57
        );
58
//        DBHelper.registerParametersDefinition(
59
//                NAME + "ResourceParameters",
60
//                PostgreSQLResourceParameters.class,
61
//                dataman.getResourceAsStream(this, NAME + "Parameters.xml")
62
//        );
63
        try {
64
            DBHelper.registerMetadataDefinition(
65
                NAME,
66
                JDBCStoreProviderBase.class,
67
                dataman.getResourceAsStream(this, NAME + "Metadata.xml")
68
            );
69
        } catch (MetadataException e) {
70
            ex = new LibraryException(this.getClass(), e);
71
        }
72

  
73
//        ResourceManagerProviderServices resman = (ResourceManagerProviderServices) DALLocator
74
//                .getResourceManager();
75
//
76
//        if (!resman.getResourceProviders().contains(NAME)) {
77
//            resman.register(NAME,
78
//                "Resource for " + NAME,
79
//                PostgreSQLResource.class,
80
//                PostgreSQLResourceParameters.class
81
//            );
82
//        }
83

  
84
        if (!dataman.getStoreProviderRegister().exits(NAME)) {
85
            dataman.registerStoreProviderFactory(new PostgreSQLStoreProviderFactory());
86
        }
87

  
88
        if (!dataman.getServerExplorerRegister().exits(NAME)) {
89
            dataman.registerServerExplorerFactory(new PostgreSQLServerExplorerFactory());
90
        }
91

  
92
        // Por compatibilidad con gvSIG 2.3 registramos otra vez la factoria con
93
        // el nombre que tenia antes.
94
        if (!dataman.getServerExplorerRegister().exits("PostgreSQLExplorer")) {
95
            dataman.registerServerExplorerFactory(new PostgreSQLServerExplorerFactory("PostgreSQLExplorer"));
96
        }
97
        Json.registerSerializer(PostgreSQLServerExplorerParameters.class);
98
        if (ex != null) {
99
            throw ex;
100
        }
101
    }
102

  
103
}
tags/org.gvsig.postgresql-2.0.202/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/PostgreSQLBuilder.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
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 3
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
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24

  
25
package org.gvsig.postgresql.dal;
26

  
27
import java.sql.Connection;
28
import java.sql.DatabaseMetaData;
29
import java.text.MessageFormat;
30
import java.util.ArrayList;
31
import java.util.List;
32
import org.apache.commons.lang3.StringUtils;
33
import org.gvsig.expressionevaluator.Formatter;
34
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
35
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
36
import org.gvsig.postgresql.dal.expressionbuilderformatter.PostgreSQLFormatter;
37

  
38
@SuppressWarnings("UseSpecificCatch")
39
public class PostgreSQLBuilder extends JDBCSQLBuilderBase {
40

  
41
    protected Formatter formatter = null;
42
    
43
    public static class Version {
44

  
45
        private final int major;
46
        private final int minor;
47
        
48
        public Version(int major, int minor) {
49
            this.major = major;
50
            this.minor = minor;
51
        }
52

  
53
        public int getMajor() {
54
            return major;
55
        }
56

  
57
        public int getMinor() {
58
            return minor;
59
        }
60
        
61
    }
62
    private Version databaseVersion = null;
63
    
64
    public Version getDatabaseVersion() {
65
        if( databaseVersion == null ) {
66
            Connection conn = null;
67
            try {
68
                conn = this.getHelper().getConnection();
69
                DatabaseMetaData metadata = conn.getMetaData();
70
                databaseVersion = new Version(
71
                    metadata.getDatabaseMajorVersion(),
72
                    metadata.getDatabaseMinorVersion()
73
                );
74
            } catch (Exception ex) {
75
                databaseVersion = new Version(0,0);
76
            } finally {
77
                this.getHelper().closeConnectionQuietly(conn);
78
            }
79
        }
80
        return databaseVersion;
81
    }
82
    
83
    public PostgreSQLBuilder(JDBCHelper helper) {
84
        super(helper);
85
        this.defaultSchema = "public";
86
        this.supportSchemas = true;
87
        this.allowAutomaticValues = true;
88
        this.geometrySupportType = this.helper.getGeometrySupportType();
89
        this.hasSpatialFunctions = this.helper.hasSpatialFunctions();
90

  
91
        this.STMT_DELETE_GEOMETRY_COLUMN_FROM_TABLE_schema_table = null;
92
        this.STMT_DELETE_GEOMETRY_COLUMN_FROM_TABLE_table = null;
93

  
94
        this.STMT_UPDATE_TABLE_STATISTICS_table = "ANALYZE {0}";
95

  
96
//        config.set(SQLConfig.ST_GeomFromEWKB, "ST_GeomFromEWKB({0}, {1})");
97
//        config.set(SQLConfig.ST_AsEWKB, "ST_AsEWKB(({0}))");        
98
//        config.set(SQLConfig.ST_ExtentAggregate, "ST_Extent({0})");        
99
//        config.set(SQLConfig.ST_UnionAggregate, "ST_Union({0})");
100
        
101
//        config.set(SQLConfig.isNull, "( ({0}) ISNULL )");
102
//        config.set(SQLConfig.notIsNull, "( ({0}) NOT NULL )");
103

  
104
    }
105
    
106
    public class PostgreSQLUpdateTableStatisticsBuilderBase extends UpdateTableStatisticsBuilderBase {
107
        @Override
108
        public List<String> toStrings() {
109
            List<String> sqls = new ArrayList<>();
110
            
111
            if( !StringUtils.isBlank(STMT_UPDATE_TABLE_STATISTICS_table) ) {
112
                // In postGIS, UpdateLayerStatistics function, don't allow to 
113
                // use the database name in the table name.
114
                String name = as_identifier(this.table.getName());
115
                if( table.has_schema()) {
116
                    name = as_identifier(this.table.getSchema()) + "." + name;
117
                }
118
                String sql = MessageFormat.format(
119
                        STMT_UPDATE_TABLE_STATISTICS_table,
120
                        name
121
                    );
122
                if( !StringUtils.isEmpty(sql) ) {
123
                    sqls.add(sql);
124
                }
125
            }
126
            return sqls;
127
        }        
128
    }
129
    protected class PostgreSQLCreateIndexBuilder extends CreateIndexBuilderBase {
130

  
131
        @Override
132
        public List<String> toStrings(Formatter formatter) {
133
            StringBuilder builder = new StringBuilder();
134
            builder.append("CREATE ");
135
//            if( this.isUnique ) {
136
//                builder.append("UNIQUE ");
137
//            }
138
            builder.append("INDEX ");
139
            if( this.ifNotExist ) {
140
                Version version = getDatabaseVersion();
141
                if( version.getMajor()>=9 && version.getMinor()>=5 ) {
142
                    builder.append("IF NOT EXISTS ");
143
                }
144
            }
145
            builder.append(as_identifier(this.indexName));
146
            builder.append(" ON ");
147
            builder.append(this.table.toString(formatter));
148
            if( this.isSpatial ) {
149
                builder.append(" USING GIST ");
150
            }
151
            builder.append(" ( ");
152
            boolean is_first_column = true;
153
            for( String column : this.columns) {
154
                if( is_first_column ) {
155
                    is_first_column = false;
156
                } else {
157
                    builder.append(", ");
158
                }
159
                builder.append(as_identifier(column));
160
            }
161
            builder.append(" )");
162
            
163
            List<String> sqls = new ArrayList<>();
164
            sqls.add(builder.toString());
165
            return sqls;
166
        }
167
        
168
    }
169
    
170
    protected class PostgreSQLCreateTableBuilder extends CreateTableBuilderBase {
171

  
172
        @Override
173
       public List<String> toStrings(Formatter formatter) {
174
           // 
175
           // https://www.postgresql.org/docs/9.1/static/sql-createtable.html
176
           //
177
            List<String> sqls = new ArrayList<>();
178
            StringBuilder builder = new StringBuilder();
179

  
180
            builder.append("CREATE TABLE ");
181
            builder.append(this.table.toString(formatter));
182
            builder.append(" (");
183
            boolean first = true;
184
            for (ColumnDescriptor column : columns) {
185
                if( column.isGeometry() ) {
186
                    continue;
187
                }
188
                if (first) {
189
                    first = false;
190
                } else {
191
                    builder.append(", ");
192
                }
193
                builder.append(as_identifier(column.getName()));
194
                builder.append(" ");
195
                if( column.isAutomatic() ) {
196
                    builder.append(" SERIAL");
197
                } else {
198
                    builder.append(sqltype(
199
                            column.getType(), 
200
                            column.getSize(),
201
                            column.getPrecision(), 
202
                            column.getScale(), 
203
                            column.getGeometryType(),
204
                            column.getGeometrySubtype()
205
                    ));
206
                    if (column.getDefaultValue() == null) {
207
                        if (column.allowNulls()) {
208
                            builder.append(" DEFAULT NULL");
209
                        }
210
                    } else {
211
                        builder.append(" DEFAULT '");
212
                        builder.append(column.getDefaultValue().toString());
213
                        builder.append("'");
214
                    }
215
                    if (column.allowNulls()) {
216
                        builder.append(" NULL");
217
                    } else {
218
                        builder.append(" NOT NULL");
219
                    }
220
                }
221
                if (column.isPrimaryKey()) {
222
                    builder.append(" PRIMARY KEY");
223
                }
224
            }
225
            builder.append(" )");
226
            sqls.add(builder.toString());
227

  
228
            String AddGeometryColumn = "SELECT AddGeometryColumn({0} , {1} , {2}, {3,number,#######} , {4} , {5}, {6})";
229
            for (ColumnDescriptor column : columns) {
230
                if( column.isGeometry() ) {
231
                    String sql = MessageFormat.format(
232
                        AddGeometryColumn,
233
                        as_string(this.table.has_schema()?this.table.getSchema():"public"),
234
                        as_string(this.table.getName()),
235
                        as_string(column.getName()),
236
                        column.getGeometrySRSId(),
237
                        as_string(sqlgeometrytype(column.getGeometryType(), column.getGeometrySubtype())),
238
                        as_string(sqlgeometrydimension(column.getGeometryType(), column.getGeometrySubtype())),
239
                        as_string(column.allowNulls())
240
                    );
241
                    sqls.add(sql);
242
                }
243
            }
244
            return sqls;
245
        }
246
    }
247

  
248
    public class PostgreSQLSelectBuilderBase extends SelectBuilderBase {
249
        
250
        @Override
251
        protected boolean isValid(StringBuilder message) {
252
            if( message == null ) {
253
                message = new StringBuilder();
254
            }
255
            if( this.has_offset() && !this.has_order_by() ) {
256
                // Algunos gestores de BBDD requieren que se especifique un
257
                // orden para poder usar OFFSET. Como eso parece buena idea para
258
                // asegurar que siempre tengamos los mismo resultados, lo exijimos
259
                // siempre.
260
                message.append("Can't use OFFSET without an ORDER BY.");
261
                return false;
262
            }
263
            return true;
264
        }        
265
        
266
        @Override
267
        public String toString(Formatter formatter) {
268
            //
269
            // https://www.postgresql.org/docs/9.1/static/sql-select.html
270
            //
271
            StringBuilder builder = new StringBuilder();
272
            if( !isValid(builder) ) {
273
                throw new IllegalStateException(builder.toString());
274
            }
275
            builder.append("SELECT ");
276
            if( this.distinct ) {
277
                builder.append("DISTINCT ");
278
            }
279
            boolean first = true;
280
            for (SelectColumnBuilder column : columns) {
281
                if (first) {
282
                    first = false;
283
                } else {
284
                    builder.append(", ");
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff