Revision 493

View differences:

tags/org.gvsig.postgresql-2.0.100/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.SQLException;
6
import org.apache.commons.dbcp.BasicDataSource;
7
import org.apache.commons.lang3.BooleanUtils;
8
import org.apache.commons.lang3.StringUtils;
9
import org.gvsig.fmap.dal.SQLBuilder;
10
import org.gvsig.fmap.dal.resource.exception.AccessResourceException;
11
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters;
12
import org.gvsig.fmap.dal.store.jdbc.JDBCNewStoreParameters;
13
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
14
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
15
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCDriverClassNotFoundException;
16
import org.gvsig.fmap.dal.store.jdbc2.OperationsFactory;
17
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCHelperBase;
18
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
19
import org.gvsig.fmap.dal.store.jdbc2.spi.SRSSolverBase;
20
import org.gvsig.postgresql.dal.operations.PostgreSQLOperationsFactory;
21
import org.slf4j.Logger;
22
import org.slf4j.LoggerFactory;
23

  
24
public class PostgreSQLHelper extends JDBCHelperBase {
25

  
26
    static final Logger logger = LoggerFactory.getLogger(PostgreSQLHelper.class);
27

  
28
    public static final String POSTGRESQL_JDBC_DRIVER = "org.postgresql.Driver";
29
    
30
    public static String getConnectionURL(PostgreSQLConnectionParameters params) {
31
        return getConnectionURL(
32
            params.getHost(),
33
            params.getPort(),
34
            params.getDBName()
35
        );
36
    }
37
    
38
    public static String getConnectionURL(String host, Integer port, String db) {
39
        if( StringUtils.isEmpty(host) ) {
40
            throw new IllegalArgumentException("Parameter 'host' can't be null.");
41
        }
42
        String connectionURL = "jdbc:postgresql://" + host;
43
        if (port != null) {
44
            connectionURL = connectionURL + ":" + port;
45
        }
46
        connectionURL = connectionURL + "/" + db;
47
        logger.debug("connectionURL: {}", connectionURL);
48
        return connectionURL;
49
    }
50

  
51
    private static class ConnectionProvider {
52

  
53
        private static boolean needRegisterDriver = true;
54

  
55
        private BasicDataSource dataSource = null;
56

  
57
        private final PostgreSQLConnectionParameters connectionParameters;
58

  
59
        public ConnectionProvider(PostgreSQLConnectionParameters connectionParameters) {
60
            this.connectionParameters = connectionParameters;
61
        }
62

  
63
        public Connection getConnection() throws SQLException {
64
            if (this.dataSource == null) {
65
                this.dataSource = this.createDataSource();               
66
            }
67
            if( logger.isDebugEnabled() ) {
68
                logger.debug("getConnection:\n" + getStatusInformation());
69
            }
70
            Connection conn;
71
            try {
72
                conn = this.dataSource.getConnection();
73
            } catch(Throwable ex) {
74
                logger.debug("Error getting connection from pool.",ex);
75
                throw ex;
76
            }
77
            if( logger.isDebugEnabled() ) {
78
                logger.debug("Created connection: {}\n  NumActive: {}\n  NumIdle: {}",
79
                    new Object[] {
80
                        conn.hashCode(), 
81
                        this.dataSource.getNumActive(),
82
                        this.dataSource.getNumIdle()
83
                    }
84
                );
85
            }
86
            return conn;
87
        }
88
        
89
        public void closeConnection(Connection connection) {
90
            if( connection != null ) {
91
                int connectionId = connection.hashCode();
92
                try {
93
                    connection.close();
94
                } catch(Throwable ex) {
95
                    logger.warn("Can't close connection.", ex);
96
                }
97
                if( logger.isDebugEnabled() ) {
98
                    Boolean isClosed;
99
                    try {
100
                        isClosed = connection.isClosed();
101
                    } catch(Throwable th) {
102
                        isClosed = null;
103
                    }
104
                    logger.debug("Closed connection: {}\n  isClosed: {}\n  NumActive: {}\n  NumIdle: {}",
105
                        new Object[] {
106
                            connectionId, 
107
                            isClosed,
108
                            this.dataSource.getNumActive(),
109
                            this.dataSource.getNumIdle()
110
                        }
111
                    );
112
                }
113
           } else if( logger.isDebugEnabled() ) {
114
               logger.debug("Close connection: null");
115
           }
116
        }
117
        
118
        public String getStatusInformation() {
119
            StringBuilder builder = new StringBuilder();
120
            builder.append("BasicDataSource pool status:\n");
121
            builder.append("  Connection URL: '").append(this.dataSource.getUrl()).append("'\n");
122
            if( this.dataSource.getInitialSize()>0 ) {
123
                builder.append("  InitialSize: ").append(this.dataSource.getInitialSize()).append(" (The initial number of connections that are created when the pool is started)\n");
124
            }
125
            if( this.dataSource.isPoolPreparedStatements() ) {
126
                builder.append("  PoolPreparedStatements: ").append(this.dataSource.isPoolPreparedStatements()).append("\n");
127
                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");
128
            }
129
            builder.append("  MaxActive: ").append(this.dataSource.getMaxActive()).append(" (The maximum number of active connections that can be allocated from this pool at the same time)\n");
130
            builder.append("  MaxIdle: ").append(this.dataSource.getMaxIdle()).append(" (The maximum number of connections that can remain idle in the pool)\n");
131
            builder.append("  NumActive:").append(this.dataSource.getNumActive()).append(" (the current number of active connections)\n");
132
            builder.append("  NumIdle:").append(this.dataSource.getNumIdle()).append(" (the current number of idle connections)\n");
133
            return builder.toString();
134
        }
135

  
136
        private BasicDataSource createDataSource() throws SQLException {
137
            if (!this.isRegistered()) {
138
                this.registerDriver();
139
            }
140
            PostgreSQLConnectionParameters params = connectionParameters;
141

  
142
            BasicDataSource ds = new BasicDataSource();
143
            ds.setMaxIdle(params.getMaxIdle());
144
            ds.setDriverClassName(params.getJDBCDriverClassName());
145
            if( params.getUseSSL() ) {
146
                String s = BooleanUtils.toStringTrueFalse(params.getUseSSL());
147
                ds.addConnectionProperty("ssl", s );
148
            }
149
            if( !StringUtils.isEmpty(params.getUser()) ) {
150
                ds.setUsername(params.getUser());
151
            }
152
            if( !StringUtils.isEmpty(params.getPassword()) ) {
153
                ds.setPassword(params.getPassword());
154
            }
155
            ds.setUrl(params.getUrl());
156

  
157
            ds.setMaxWait(60L * 1000);
158
            return ds;
159
        }
160

  
161
        private boolean isRegistered() {
162
            return needRegisterDriver;
163
        }
164

  
165
        public void registerDriver() throws SQLException {
166
            String className = this.connectionParameters.getJDBCDriverClassName();
167
            if (className == null) {
168
                return;
169
            }
170
            try {
171
                Class theClass = Class.forName(className);
172
                if (theClass == null) {
173
                    throw new JDBCDriverClassNotFoundException(PostgreSQLLibrary.NAME, className);
174
                }
175
            } catch (Exception e) {
176
                throw new SQLException("Can't register JDBC driver '" + className + "'.", e);
177
            }
178
            needRegisterDriver = false;
179
        }
180

  
181
    }
182

  
183
    private ConnectionProvider connectionProvider = null;
184
   
185
    public PostgreSQLHelper(JDBCConnectionParameters connectionParameters) {
186
        super(connectionParameters);
187
        this.srssolver = new SRSSolverBase(this);
188
    }
189

  
190
    @Override
191
    public Connection getConnection() throws AccessResourceException {
192
        try {
193
            if (this.connectionProvider == null) {
194
                this.connectionProvider = new ConnectionProvider(this.getConnectionParameters());
195
            }
196
            return this.connectionProvider.getConnection();
197
        } catch (SQLException ex) {
198
            throw new AccessResourceException(PostgreSQLLibrary.NAME, ex);
199
        }
200
    }
201

  
202
    @Override
203
    public void closeConnection(Connection connection) {
204
         this.connectionProvider.closeConnection(connection);
205
    }
206
    
207
    @Override
208
    public PostgreSQLConnectionParameters getConnectionParameters() {
209
        return (PostgreSQLConnectionParameters) super.getConnectionParameters();
210
    }
211
    
212
    @Override
213
    public String getConnectionURL() {
214
        return getConnectionURL(this.getConnectionParameters());
215
    }
216

  
217
    @Override
218
    protected String getResourceType() {
219
        return PostgreSQLLibrary.NAME;
220
    }
221

  
222
    @Override
223
    public String getProviderName() {
224
        return PostgreSQLLibrary.NAME;
225
    }
226

  
227
    @Override
228
    public JDBCSQLBuilderBase createSQLBuilder() {
229
        return new PostgreSQLBuilder(this);
230
    }
231
    
232
    @Override
233
    public OperationsFactory getOperations() {
234
        if (this.operationsFactory == null) {
235
            this.operationsFactory = new PostgreSQLOperationsFactory(this);
236
        }
237
        return operationsFactory;
238
    }
239

  
240
    @Override
241
    public SQLBuilder.GeometrySupportType getGeometrySupportType() {
242
        return SQLBuilder.GeometrySupportType.WKB;
243
    }
244

  
245
    @Override
246
    public boolean hasSpatialFunctions() {
247
        return true;
248
    }
249

  
250
    @Override
251
    public boolean canWriteGeometry(int geometryType, int geometrySubtype) {
252
        return true;
253
    }
254

  
255
    @Override
256
    public String getQuoteForIdentifiers() {
257
        return "\"";
258
    }
259

  
260
    @Override
261
    public boolean allowAutomaticValues() {
262
        return true;
263
    }
264

  
265
    @Override
266
    public boolean supportOffsetInSelect() {
267
        return true;
268
    }
269

  
270
    @Override
271
    public String getQuoteForStrings() {
272
        return "'";
273
    }
274
    
275
    @Override
276
    public String getSourceId(JDBCStoreParameters parameters) {
277
        return parameters.getDBName() + "." + 
278
               parameters.getSchema()+ "." + 
279
               parameters.getTable();
280
    }
281

  
282
    @Override
283
    public JDBCNewStoreParameters createNewStoreParameters() {
284
        return new PostgreSQLNewStoreParameters();
285
    }
286

  
287
    @Override
288
    public JDBCStoreParameters createOpenStoreParameters() {
289
        return new PostgreSQLStoreParameters();
290
    }
291

  
292
    @Override
293
    public JDBCServerExplorerParameters createServerExplorerParameters() {
294
        return new PostgreSQLServerExplorerParameters();
295
    }
296
}
tags/org.gvsig.postgresql-2.0.100/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.100/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/PostgreSQLStoreProviderFactory.java
1

  
2
package org.gvsig.postgresql.dal;
3

  
4
import org.gvsig.fmap.dal.DataParameters;
5
import org.gvsig.fmap.dal.exception.InitializeException;
6
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
7
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters;
8
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
9
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
10
import org.gvsig.fmap.dal.store.jdbc2.JDBCStoreProvider;
11
import org.gvsig.fmap.dal.store.jdbc2.impl.JDBCStoreProviderFactory;
12

  
13

  
14
public class PostgreSQLStoreProviderFactory extends JDBCStoreProviderFactory {
15
    
16
    public PostgreSQLStoreProviderFactory() {
17
        super(
18
                PostgreSQLLibrary.NAME, 
19
                "PostgreSQL store"
20
        );
21
    }
22

  
23
    @Override
24
    public JDBCStoreProvider createProvider(
25
            DataParameters parameters,
26
            DataStoreProviderServices providerServices
27
    ) throws InitializeException {
28
        JDBCHelper helper = new PostgreSQLHelper((JDBCConnectionParameters) parameters);
29
        JDBCStoreProvider provider = helper.createProvider(
30
                (JDBCStoreParameters) parameters, 
31
                providerServices
32
        );
33
        return provider;
34
    }
35

  
36
    @Override
37
    public JDBCStoreParameters createParameters() {
38
        JDBCStoreParameters params = new PostgreSQLStoreParameters();
39
        return params;
40
    }
41
    
42
}
tags/org.gvsig.postgresql-2.0.100/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.fmap.dal.DataTypes;
15
import org.gvsig.fmap.dal.exception.DataException;
16
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
17
import org.gvsig.fmap.dal.feature.EditableFeatureType;
18
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
19
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
20
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
21
import org.gvsig.fmap.dal.store.jdbc2.spi.SRSSolver;
22
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.FetchFeatureTypeOperation;
23
import org.gvsig.fmap.geom.Geometry;
24
import org.gvsig.fmap.geom.GeometryLocator;
25
import org.gvsig.fmap.geom.GeometryManager;
26
import org.gvsig.fmap.geom.type.GeometryType;
27

  
28
public class PostgreSQLFetchFeatureTypeOperation extends FetchFeatureTypeOperation {
29

  
30
    private static Map<String,GeometryType>databaseGeometryTypes = null;
31
    
32
    public PostgreSQLFetchFeatureTypeOperation(
33
            JDBCHelper helper
34
        ) {
35
        super(helper);
36
    }
37

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

  
63
    @Override
64
    public void fetch(EditableFeatureType featureType, Connection conn, String dbname, String schema, String table, List<String> pks, String defaultGeometryColumn, IProjection crs) throws DataException {
65
        super.fetch(featureType, conn, dbname, schema, table, pks, defaultGeometryColumn, crs);
66
    }
67

  
68
    @Override
69
    protected int getDataTypeFromMetadata(
70
            ResultSetMetaData rsMetadata,
71
            int colIndex
72
        ) throws SQLException {
73

  
74
        return super.getDataTypeFromMetadata(rsMetadata, colIndex);
75
    }
76
        
77
    @Override
78
    protected void fetchGeometryTypeAndSRS(
79
            EditableFeatureAttributeDescriptor attr,
80
            ResultSetMetaData rsMetadata,
81
            int colIndex
82
        ) {
83
        if( attr.getType()!=DataTypes.GEOMETRY ) {
84
            return;
85
        }
86
        try {
87
            JDBCSQLBuilderBase sqlbuilder = this.createSQLBuilder();
88
            sqlbuilder.select().column().name("f_table_catalog");
89
            sqlbuilder.select().column().name("f_table_schema");
90
            sqlbuilder.select().column().name("f_table_name");
91
            sqlbuilder.select().column().name("f_geometry_column");
92
            sqlbuilder.select().column().name("coord_dimension");
93
            sqlbuilder.select().column().name("srid");
94
            sqlbuilder.select().column().name("type");
95
            sqlbuilder.select().where().set(
96
                    sqlbuilder.eq(
97
                            sqlbuilder.column("f_table_name"),
98
                            sqlbuilder.constant(this.getTablename())
99
                    )
100
            );                
101
            sqlbuilder.select().where().and(
102
                    sqlbuilder.eq(
103
                            sqlbuilder.column("f_geometry_column"),
104
                            sqlbuilder.constant(attr.getName())
105
                    )
106
            );         
107
            sqlbuilder.select().from().table().name("geometry_columns");
108
            Statement st = null;
109
            ResultSet rs = null;
110
            
111
            Integer srsid = null;
112
            String geometryTypeName = null;
113
            try {
114
                st = this.getConnection().createStatement();
115
                rs = JDBCUtils.executeQuery(st, sqlbuilder.toString());
116
                if (rs.next()) {
117
                    srsid = rs.getInt("srid");
118
                    geometryTypeName = rs.getString("type");
119
                }
120
            } finally {
121
                JDBCUtils.closeQuietly(rs);
122
                JDBCUtils.closeQuietly(st);
123
            }
124
            if( !StringUtils.isEmpty(geometryTypeName) ) {
125
                GeometryType gt = getGeometryTypeFromDatabaseTypeName(geometryTypeName);
126
                attr.setGeometryType(gt);
127
            }
128
            if( srsid!=null ) {
129
                SRSSolver srssolver = this.helper.getSRSSolver();
130
                attr.setSRS(srssolver.getProjection(this.getConnection(),srsid));
131
            }
132
        } catch (Exception ex) {
133
            logger.debug("Can't get geometry type and srs from column '"+attr.getName()+"'.",ex);
134
        }
135
    }
136

  
137
    private GeometryType getGeometryTypeFromDatabaseTypeName(String typeName) {
138
        if( databaseGeometryTypes==null ) {
139
            GeometryManager manager = GeometryLocator.getGeometryManager();
140
            databaseGeometryTypes = new HashMap<>();
141
            databaseGeometryTypes.put("POINT", getGT(manager, Geometry.TYPES.POINT,Geometry.SUBTYPES.GEOM2D));
142
            databaseGeometryTypes.put("POINTZ", getGT(manager, Geometry.TYPES.POINT,Geometry.SUBTYPES.GEOM3D));
143
            databaseGeometryTypes.put("POINTM", getGT(manager, Geometry.TYPES.POINT,Geometry.SUBTYPES.GEOM2DM));
144
            databaseGeometryTypes.put("POINTZM", getGT(manager, Geometry.TYPES.POINT,Geometry.SUBTYPES.GEOM3DM));
145
            
146
            databaseGeometryTypes.put("LINESTRING", getGT(manager, Geometry.TYPES.LINE,Geometry.SUBTYPES.GEOM2D));
147
            databaseGeometryTypes.put("LINESTRINGZ", getGT(manager, Geometry.TYPES.LINE,Geometry.SUBTYPES.GEOM3D));
148
            databaseGeometryTypes.put("LINESTRINGM", getGT(manager, Geometry.TYPES.LINE,Geometry.SUBTYPES.GEOM2DM));
149
            databaseGeometryTypes.put("LINESTRINGZM", getGT(manager, Geometry.TYPES.LINE,Geometry.SUBTYPES.GEOM3DM));
150
            
151
            databaseGeometryTypes.put("POLYGON", getGT(manager, Geometry.TYPES.POLYGON,Geometry.SUBTYPES.GEOM2D));
152
            databaseGeometryTypes.put("POLYGONZ", getGT(manager, Geometry.TYPES.POLYGON,Geometry.SUBTYPES.GEOM3D));
153
            databaseGeometryTypes.put("POLYGONM", getGT(manager, Geometry.TYPES.POLYGON,Geometry.SUBTYPES.GEOM2DM));
154
            databaseGeometryTypes.put("POLYGONZM", getGT(manager, Geometry.TYPES.POLYGON,Geometry.SUBTYPES.GEOM3DM));
155

  
156
            databaseGeometryTypes.put("MULTIPOINT", getGT(manager, Geometry.TYPES.MULTIPOINT,Geometry.SUBTYPES.GEOM2D));
157
            databaseGeometryTypes.put("MULTIPOINTZ", getGT(manager, Geometry.TYPES.MULTIPOINT,Geometry.SUBTYPES.GEOM3D));
158
            databaseGeometryTypes.put("MULTIPOINTM", getGT(manager, Geometry.TYPES.MULTIPOINT,Geometry.SUBTYPES.GEOM2DM));
159
            databaseGeometryTypes.put("MULTIPOINTZM", getGT(manager, Geometry.TYPES.MULTIPOINT,Geometry.SUBTYPES.GEOM3DM));
160

  
161
            databaseGeometryTypes.put("MULTILINESTRING", getGT(manager, Geometry.TYPES.MULTILINE,Geometry.SUBTYPES.GEOM2D));
162
            databaseGeometryTypes.put("MULTILINESTRINGZ", getGT(manager, Geometry.TYPES.MULTILINE,Geometry.SUBTYPES.GEOM3D));
163
            databaseGeometryTypes.put("MULTILINESTRINGM", getGT(manager, Geometry.TYPES.MULTILINE,Geometry.SUBTYPES.GEOM2DM));
164
            databaseGeometryTypes.put("MULTILINESTRINGZM", getGT(manager, Geometry.TYPES.MULTILINE,Geometry.SUBTYPES.GEOM3DM));
165

  
166
            databaseGeometryTypes.put("MULTIPOLYGON", getGT(manager, Geometry.TYPES.MULTIPOLYGON,Geometry.SUBTYPES.GEOM2D));
167
            databaseGeometryTypes.put("MULTIPOLYGONZ", getGT(manager, Geometry.TYPES.MULTIPOLYGON,Geometry.SUBTYPES.GEOM3D));
168
            databaseGeometryTypes.put("MULTIPOLYGONM", getGT(manager, Geometry.TYPES.MULTIPOLYGON,Geometry.SUBTYPES.GEOM2DM));
169
            databaseGeometryTypes.put("MULTIPOLYGONZM", getGT(manager, Geometry.TYPES.MULTIPOLYGON,Geometry.SUBTYPES.GEOM3DM));
170

  
171
            databaseGeometryTypes.put("GEOMETRY", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM2D));
172
            databaseGeometryTypes.put("GEOMETRYZ", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM3D));
173
            databaseGeometryTypes.put("GEOMETRYM", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM2DM));
174
            databaseGeometryTypes.put("GEOMETRYZM", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM3DM));
175
        }
176
        return databaseGeometryTypes.get(typeName);
177
    }
178
    
179
}
tags/org.gvsig.postgresql-2.0.100/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, String database, String schema, String table, List<String> primaryKeys, String defaultGeometryField, IProjection crs) {
20
        return new PostgreSQLFetchFeatureTypeOperation(
21
                helper, type, database, schema, table, primaryKeys, 
22
                defaultGeometryField, crs
23
        );
24
    }  
25
    
26
}
tags/org.gvsig.postgresql-2.0.100/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

  
65
}
tags/org.gvsig.postgresql-2.0.100/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/PostgreSQLConnectionParameters.java
1

  
2
package org.gvsig.postgresql.dal;
3

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

  
7
public interface PostgreSQLConnectionParameters extends JDBCConnectionParameters, DBParameters {
8
	public static final String USESSL_PARAMTER_NAME = "UseSSL";
9
	public static final String MAXIDLE_PARAMTER_NAME = "maxIdle";
10

  
11
	public boolean getUseSSL();   
12
    
13
    public int getMaxIdle();
14
}
tags/org.gvsig.postgresql-2.0.100/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
}
tags/org.gvsig.postgresql-2.0.100/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.metadata.exceptions.MetadataException;
11
import org.gvsig.tools.library.AbstractLibrary;
12
import org.gvsig.tools.library.LibraryException;
13

  
14

  
15
public class PostgreSQLLibrary extends AbstractLibrary {
16

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

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

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

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

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

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

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

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

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

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

  
102
}
tags/org.gvsig.postgresql-2.0.100/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.fmap.dal.store.jdbc2.JDBCHelper;
34
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
35

  
36
public class PostgreSQLBuilder extends JDBCSQLBuilderBase {
37

  
38
    private int[] databaseVersion = null;
39
    
40
    protected int[] getDatabaseVersion() {
41
        if( databaseVersion == null ) {
42
            Connection conn;
43
            try {
44
                conn = this.getHelper().getConnection();
45
                DatabaseMetaData metadata = conn.getMetaData();
46
                databaseVersion =  new int[] {
47
                    metadata.getDatabaseMajorVersion(),
48
                    metadata.getDatabaseMinorVersion()
49
                };
50
            } catch (Exception ex) {
51
                databaseVersion = new int[] { 0,0 };
52
            }
53
        }
54
        return databaseVersion;
55
    }
56
    
57
    public PostgreSQLBuilder(JDBCHelper helper) {
58
        super(helper);
59
              
60
        config.set(SQLConfig.default_schema, "public");
61
        config.set(SQLConfig.allowAutomaticValues, true);
62
        config.set(SQLConfig.geometry_type_support, this.helper.getGeometrySupportType());
63
        config.set(SQLConfig.has_spatial_functions, this.helper.hasSpatialFunctions());
64
        config.set(SQLConfig.constant_true, "true");
65
        config.set(SQLConfig.constant_false, "false");
66
            
67
        config.remove_functionality(SQLConfig.DELETE_GEOMETRY_COLUMN_FROM_TABLE_schema_table);
68
        config.remove_functionality(SQLConfig.DELETE_GEOMETRY_COLUMN_FROM_TABLE_table);
69
         
70
        config.set(SQLConfig.UPDATE_TABLE_STATISTICS_table,"ANALYZE {0}");
71

  
72
        config.set(SQLConfig.ST_GeomFromEWKB, "ST_GeomFromEWKB({0}, {1})");
73
        config.set(SQLConfig.ST_AsEWKB, "ST_AsEWKB(({0}))");        
74
        config.set(SQLConfig.ST_ExtentAggregate, "ST_Extent({0})");        
75
        config.set(SQLConfig.ST_UnionAggregate, "ST_Union({0})");
76
        
77
        config.set(SQLConfig.lcase, "lower({0})");
78
        config.set(SQLConfig.ucase, "upper({0})");
79
        config.set(SQLConfig.operator_ILIKE, "({0}) ILIKE ({1})");
80
        config.set(SQLConfig.isNull, "( ({0}) ISNULL )");
81
        config.set(SQLConfig.notIsNull, "( ({0}) NOT NULL )");
82

  
83
    }
84
    
85
    public class PostgreSQLUpdateTableStatisticsBuilderBase extends UpdateTableStatisticsBuilderBase {
86
        @Override
87
        public List<String> toStrings() {
88
            List<String> sqls = new ArrayList<>();
89
            
90
            if( config.has_functionality(SQLConfig.UPDATE_TABLE_STATISTICS_table) ) {
91
                // In postGIS, UpdateLayerStatistics function, don't allow to 
92
                // use the database name in the table name.
93
                String name = identifier(this.table.getName());
94
                if( table.has_schema()) {
95
                    name = identifier(this.table.getSchema()) + "." + name;
96
                }
97
                String sql = MessageFormat.format(
98
                        config.getString(SQLConfig.UPDATE_TABLE_STATISTICS_table),
99
                        name
100
                    );
101
                if( !StringUtils.isEmpty(sql) ) {
102
                    sqls.add(sql);
103
                }
104
            }
105
            return sqls;
106
        }        
107
    }
108
    protected class PostgreSQLCreateIndexBuilder extends CreateIndexBuilderBase {
109

  
110
        @Override
111
        public List<String> toStrings() {
112
            StringBuilder builder = new StringBuilder();
113
            builder.append("CREATE ");
114
//            if( this.isUnique ) {
115
//                builder.append("UNIQUE ");
116
//            }
117
            builder.append("INDEX ");
118
            if( this.ifNotExist ) {
119
                int[] version = getDatabaseVersion();
120
                if( version[0]>=9 && version[1]>=5 ) {
121
                    builder.append("IF NOT EXISTS ");
122
                }
123
            }
124
            builder.append(identifier(this.indexName));
125
            builder.append(" ON ");
126
            builder.append(this.table.toString());
127
            if( this.isSpatial ) {
128
                builder.append(" USING GIST ");
129
            }
130
            builder.append(" ( ");
131
            boolean is_first_column = true;
132
            for( String column : this.columns) {
133
                if( is_first_column ) {
134
                    is_first_column = false;
135
                } else {
136
                    builder.append(", ");
137
                }
138
                builder.append(column);
139
            }
140
            builder.append(" )");
141
            
142
            List<String> sqls = new ArrayList<>();
143
            sqls.add(builder.toString());
144
            return sqls;
145
        }
146
        
147
    }
148
    
149
    protected class PostgreSQLCreateTableBuilder extends CreateTableBuilderBase {
150

  
151
        @Override
152
       public List<String> toStrings() {
153
           // 
154
           // https://www.postgresql.org/docs/9.1/static/sql-createtable.html
155
           //
156
            List<String> sqls = new ArrayList<>();
157
            StringBuilder builder = new StringBuilder();
158

  
159
            builder.append("CREATE TABLE ");
160
            builder.append(this.table.toString());
161
            builder.append(" (");
162
            boolean first = true;
163
            for (ColumnDescriptor column : columns) {
164
                if( column.isGeometry() ) {
165
                    continue;
166
                }
167
                if (first) {
168
                    first = false;
169
                } else {
170
                    builder.append(", ");
171
                }
172
                builder.append(identifier(column.getName()));
173
                builder.append(" ");
174
                if( column.isAutomatic() ) {
175
                    builder.append(" SERIAL");
176
                } else {
177
                    builder.append(sqltype(column.getType(), column.getPrecision(), column.getSize()));
178
                    if (column.getDefaultValue() == null) {
179
                        if (column.allowNulls()) {
180
                            builder.append(" DEFAULT NULL");
181
                        }
182
                    } else {
183
                        builder.append(" DEFAULT '");
184
                        builder.append(column.getDefaultValue().toString());
185
                        builder.append("'");
186
                    }
187
                    if (column.allowNulls()) {
188
                        builder.append(" NULL");
189
                    } else {
190
                        builder.append(" NOT NULL");
191
                    }
192
                }
193
                if (column.isPrimaryKey()) {
194
                    builder.append(" PRIMARY KEY");
195
                }
196
            }
197
            builder.append(" )");
198
            sqls.add(builder.toString());
199

  
200
            String AddGeometryColumn = "SELECT AddGeometryColumn({0} , {1} , {2}, {3,number,#######} , {4} , {5}, {6})";
201
            for (ColumnDescriptor column : columns) {
202
                if( column.isGeometry() ) {
203
                    String sql = MessageFormat.format(
204
                        AddGeometryColumn,
205
                        constant(this.table.getSchema()),
206
                        constant(this.table.getName()),
207
                        constant(column.getName()),
208
                        column.getGeometrySRSId(),
209
                        constant(sqlgeometrytype(column.getGeometryType(), column.getGeometrySubtype())),
210
                        constant(sqlgeometrydimension(column.getGeometryType(), column.getGeometrySubtype())),
211
                        constant(column.allowNulls())
212
                    );
213
                    sqls.add(sql);
214
                }
215
            }
216
            return sqls;
217
        }
218
    }
219

  
220
    public class PostgreSQLSelectBuilderBase extends SelectBuilderBase {
221
        
222
        @Override
223
        protected boolean isValid(StringBuilder message) {
224
            if( message == null ) {
225
                message = new StringBuilder();
226
            }
227
            if( this.has_offset() && !this.has_order_by() ) {
228
                // Algunos gestores de BBDD requieren que se especifique un
229
                // orden para poder usar OFFSET. Como eso parece buena idea para
230
                // asegurar que siempre tengamos los mismo resultados, lo exijimos
231
                // siempre.
232
                message.append("Can't use OFFSET without an ORDER BY.");
233
                return false;
234
            }
235
            return true;
236
        }        
237
        
238
        @Override
239
        public String toString() {
240
            //
241
            // https://www.postgresql.org/docs/9.1/static/sql-select.html
242
            //
243
            StringBuilder builder = new StringBuilder();
244
            if( !isValid(builder) ) {
245
                throw new IllegalStateException(builder.toString());
246
            }
247
            builder.append("SELECT ");
248
            if( this.distinct ) {
249
                builder.append("DISTINCT ");
250
            }
251
            boolean first = true;
252
            for (SelectColumnBuilder column : columns) {
253
                if (first) {
254
                    first = false;
255
                } else {
256
                    builder.append(", ");
257
                }
258
                builder.append(column.toString());
259
            }
260

  
261
            if ( this.has_from() ) {
262
                builder.append(" FROM ");
263
                builder.append(this.from.toString());
264
            }
265
            if ( this.has_where() ) {
266
                builder.append(" WHERE ");
267
                builder.append(this.where.toString());
268
            }
269
            
270
            if( this.has_order_by() ) {
271
                builder.append(" ORDER BY ");
272
                first = true;
273
                for (OrderByBuilder item : this.order_by) {
274
                    if (first) {
275
                        first = false;
276
                    } else {
277
                        builder.append(", ");
278
                    }
279
                    builder.append(item.toString());                    
280
                }   
281
            }
282
            
283
            if ( this.has_limit() && this.has_offset() ) {
284
                builder.append(" OFFSET ");
285
                builder.append(this.offset);
286
                builder.append(" FETCH NEXT ");
287
                builder.append(this.limit);
288
                builder.append(" ROWS ONLY");
289

  
290
            } else if ( this.has_limit()) {
291
                builder.append(" LIMIT ");
292
                builder.append(this.limit);
293

  
294
            } else if ( this.has_offset() ) {
295
                builder.append(" LIMIT ALL OFFSET ");
296
                builder.append(this.offset);    
297
            }
298
            return builder.toString();
299

  
300
        }
301
    }
302

  
303
    @Override
304
    public String bytearray(byte[] data) {
305
        return "decode('"+bytearray_hex(data)+"','hex')";
306
    }
307

  
308
    public PostgreSQLHelper getHelper() {
309
        return (PostgreSQLHelper) helper;
310
    }
311
    
312
    @Override
313
    protected CreateTableBuilder createCreateTableBuilder() {
314
        return new PostgreSQLCreateTableBuilder();
315
    }
316

  
317
    @Override
318
    protected CreateIndexBuilder createCreateIndexBuilder() {
319
        return new PostgreSQLCreateIndexBuilder();
320
    }
321

  
322
    @Override
323
    protected SelectBuilder createSelectBuilder() {
324
        return new PostgreSQLSelectBuilderBase();
325
    }
326

  
327
    @Override
328
    protected UpdateTableStatisticsBuilder createUpdateTableStatisticsBuilder() {
329
        return new PostgreSQLUpdateTableStatisticsBuilderBase();
330
    }       
331
   
332
}
tags/org.gvsig.postgresql-2.0.100/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/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.postgresql.dal;
23

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

  
27
public class PostgreSQLNewStoreParameters 
28
    extends 
29
        JDBCNewStoreParameters 
30
    implements 
31
        PostgreSQLConnectionParameters 
32
    {
33

  
34
    private final PostgreSQLConnectionParametersHelper helper;
35
    
36
    public PostgreSQLNewStoreParameters() {
37
        super(
38
            PostgreSQLLibrary.NAME + "NewStoreParameters", 
39
            PostgreSQLLibrary.NAME
40
        );
41
        this.helper = new PostgreSQLConnectionParametersHelper(this);
42
    }
43

  
44
    @Override
45
    public String getUrl() {
46
        return this.helper.getUrl();
47
    }
48
    
49
    @Override
50
    public void validate() throws ValidateDataParametersException {
51
        this.helper.validate();
52
    }
53
        
54
    @Override
55
    public boolean getUseSSL() {
56
        return this.helper.getUseSSL();
57
    }
58

  
59
    @Override
60
    public int getMaxIdle() {
61
        return this.helper.getMaxIdle();
62
    }
63

  
64
    public void setUseSSL(boolean v) {
65
        this.helper.setUseSSL(v);
66
    }
67

  
68
}
tags/org.gvsig.postgresql-2.0.100/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/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
 */
25
package org.gvsig.postgresql.dal;
26

  
27
import org.apache.commons.lang3.StringUtils;
28
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
29
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
30
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
31

  
32
             
33
public class PostgreSQLServerExplorerParameters extends
34
        JDBCServerExplorerParameters 
35
    implements
36
        PostgreSQLConnectionParameters
37
    {
38
    
39
    private final PostgreSQLConnectionParametersHelper helper;
40

  
41
    public PostgreSQLServerExplorerParameters() {
42
        super(
43
                PostgreSQLLibrary.NAME + "ServerExplorerParameters",
44
                PostgreSQLLibrary.NAME
45
        );
46
        this.helper = new PostgreSQLConnectionParametersHelper(this);
47
    }
48

  
49
    @Override
50
    public String getUrl() {
51
        return this.helper.getUrl();
52
    }
53
    
54
    @Override
55
    public void validate() throws ValidateDataParametersException {
56
        // Esto seria para convertir los parametros de gvSIG 2.3 a 2.4.
57
//        if( !StringUtils.equalsIgnoreCase(PostgreSQLLibrary.NAME, (CharSequence) getDynValue(DataStoreProviderServices.PROVIDER_PARAMTER_NAME)) ) {
58
//            setDynValue(DataStoreProviderServices.PROVIDER_PARAMTER_NAME, PostgreSQLLibrary.NAME);
59
//        }
60
        this.helper.validate();
61
        super.validate();        
62
    }
63

  
64
    @Override
65
    public boolean getUseSSL() {
66
        return this.helper.getUseSSL();
67
    }
68

  
69
    @Override
70
    public int getMaxIdle() {
71
        return this.helper.getMaxIdle();
72
    }
73

  
74
    public void setUseSSL(boolean v) {
75
        this.helper.setUseSSL(v);
76
    }
77
}
tags/org.gvsig.postgresql-2.0.100/org.gvsig.postgresql.provider/src/main/resources/org/gvsig/postgresql/dal/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="JDBC2" 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.100/org.gvsig.postgresql.provider/src/main/resources/org/gvsig/postgresql/dal/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>JDBC2ResourceParameters</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
        <field name="maxIdle" type="integer" mandatory="false"
27
          defaultValue="8" group="Advanced">
28
          <description>The maximum number of connections that can remail idle in the pool.</description>
29
        </field>
30
      </fields>
31
    </class>
32

  
33
    <class name="PostgreSQLStoreParameters">
34
      <extends>
35
        <class>JDBC2StoreParameters</class>
36
        <class>PostgreSQLResourceParameters</class>
37
      </extends>
38
      <fields/>
39
    </class>
40

  
41
    <class name="PostgreSQLNewStoreParameters">
42
      <extends>
43
        <class>JDBC2NewStoreParameters</class>
44
        <class>PostgreSQLResourceParameters</class>
45
      </extends>
46
      <fields/>
47
    </class>
48

  
49

  
50
    <class name="PostgreSQLServerExplorerParameters">
51
      <extends>
52
        <class>PostgreSQLResourceParameters</class>
53
        <class>JDBC2ServerExplorerParameters</class>
54
      </extends>
55
      <fields/>
56
    </class>
57

  
58

  
59
  </classes>
60
</definitions>  
tags/org.gvsig.postgresql-2.0.100/org.gvsig.postgresql.provider/src/main/resources/META-INF/services/org.gvsig.tools.library.Library
1
org.gvsig.postgresql.dal.PostgreSQLLibrary
tags/org.gvsig.postgresql-2.0.100/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>
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff