Revision 43687

View differences:

trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.db/org.gvsig.fmap.dal.db.h2/src/main/java/org/gvsig/fmap/dal/store/h2/H2SpatialSQLBuilder.java
17 17

  
18 18
public class H2SpatialSQLBuilder extends JDBCSQLBuilderBase {
19 19

  
20
    private final H2SpatialHelper helper;
21

  
22 20
    public H2SpatialSQLBuilder(H2SpatialHelper helper) {
23
        super();
21
        super(helper);
24 22
        
25
        this.helper = helper;
26
        
27 23
        //
28 24
        // H2/H2GIS SQL functions reference list
29 25
        //
......
47 43
         
48 44
//        config.set(SQLConfig.UPDATE_TABLE_STATISTICS_table,"ANALYZE TABLE {0} SAMPLE_SIZE 0");
49 45
        config.set(SQLConfig.UPDATE_TABLE_STATISTICS_table,"ANALYZE SAMPLE_SIZE 0");
50
        config.set(SQLConfig.CREATE_INDEX_name_ON_table_column, "CREATE INDEX IF NOT EXISTS {0} ON {1} (\"{2}\")");
51
        config.set(SQLConfig.CREATE_INDEX_name_ON_table_USING_GIST_column, "CREATE SPATIAL INDEX IF NOT EXISTS {0} ON {1} (\"{2}\")");
52 46

  
53 47
        config.set(SQLConfig.ST_GeomFromEWKB, "GeomFromWKB({0}, {1})");
54 48
        config.set(SQLConfig.ST_AsEWKB, "AsWKB(({0}))");        
......
98 92
        }
99 93
        
100 94
    }
95

  
96
    public class H2SpatialCreateIndexBuilder extends CreateIndexBuilderBase {
101 97
    
98
        @Override
99
        public List<String> toStrings() {
100
            StringBuilder builder = new StringBuilder();
101
            builder.append("CREATE ");
102
            if( this.isUnique ) {
103
                builder.append("UNIQUE ");
104
            }
105
            if( this.isSpatial ) {
106
                builder.append("SPATIAL ");
107
            }
108
            builder.append("INDEX ");
109
            if( this.ifNotExist ) {
110
                builder.append("IF NOT EXISTS ");
111
            }
112
            builder.append(identifier(this.indexName));
113
            builder.append(" ON ");
114
            builder.append(this.table.toString());
115
            builder.append(" ( ");
116
            boolean is_first_column = true;
117
            for( String column : this.columns) {
118
                if( is_first_column ) {
119
                    is_first_column = false;
120
                } else {
121
                    builder.append(", ");
122
                }
123
                builder.append(column);
124
            }
125
            builder.append(" )");
126
            
127
            List<String> sqls = new ArrayList<>();
128
            sqls.add(builder.toString());
129
            return sqls;
130
        }
131

  
132
    }
133
        
102 134
    protected class H2SpatialAlterTableBuilderBase extends AlterTableBuilderBase {
103 135
        @Override
104 136
        public List<String> toStrings() {
105 137
            List<String> sqls = new ArrayList<>();
138
            if( this.isEmpty() ) {
139
                return sqls;
140
            }
106 141
            for (String column : drops) {
107 142
                StringBuilder builder = new StringBuilder();
108 143
                builder.append("ALTER TABLE ");
......
150 185
                }
151 186
                sqls.add(builder.toString());
152 187
                
153
                if( column.isIndexed() ) {
154
                    String sql;
155
                    String name = "idx_" + this.table().getName() + "_" + column.getName();
156
                    if( column.isGeometry() ) {
157
                        sql = MessageFormat.format(
158
                            config.getString(SQLConfig.CREATE_INDEX_name_ON_table_USING_GIST_column),
159
                            name,
160
                            this.table().toString(),
161
                            column.getName()
162
                        );
163
                    } else {
164
                        sql = MessageFormat.format(
165
                            config.getString(SQLConfig.CREATE_INDEX_name_ON_table_column),
166
                            name,
167
                            this.table().toString(),
168
                            column.getName()
169
                        );
170
                    }
171
                    sqls.add(sql);
172
                }
173

  
174 188
                if( column.isGeometry() ) {
175 189
                    String sql;
176 190
                    String constraint_name = "constraint_" + this.table().getName() + "_" + column.getName()+"_dim";
......
213 227
                    builder.append(" AUTO_INCREMENT");
214 228
                }
215 229
                sqls.add(builder.toString());
216
                if( column.isIndexed() ) {
217
                    String sql;
218
                    String name = "idx_" + this.table().getName() + "_" + column.getName();
219
                    if( column.isGeometry() ) {
220
                        sql = MessageFormat.format(
221
                            config.getString(SQLConfig.CREATE_INDEX_name_ON_table_USING_GIST_column),
222
                            name,
223
                            this.table().toString(),
224
                            column.getName()
225
                        );
226
                    } else {
227
                        sql = MessageFormat.format(
228
                            config.getString(SQLConfig.CREATE_INDEX_name_ON_table_column),
229
                            name,
230
                            this.table().toString(),
231
                            column.getName()
232
                        );
233
                    }
234
                    sqls.add(sql);
235
                }
236 230
                if( column.isGeometry() ) {
237 231
                    String sql;
238 232
                    String constraint_name = "constraint_" + this.table().getName() + "_" + column.getName()+"_dim";
......
322 316
            builder.append(" )");
323 317
            sqls.add(builder.toString());
324 318
            for (ColumnDescriptorBuilderBase column : columns) {
325
                if( column.isIndexed() ) {
326
                    String sql;
327
                    String name = "idx_" + this.table().getName() + "_" + column.getName();
328
                    if( column.isGeometry() ) {
329
                        sql = MessageFormat.format(
330
                            config.getString(SQLConfig.CREATE_INDEX_name_ON_table_USING_GIST_column),
331
                            name,
332
                            this.table().toString(),
333
                            column.getName()
334
                        );
335
                    } else {
336
                        sql = MessageFormat.format(
337
                            config.getString(SQLConfig.CREATE_INDEX_name_ON_table_column),
338
                            name,
339
                            this.table().toString(),
340
                            column.getName()
341
                        );
342
                    }
343
                    sqls.add(sql);
344
                    
345
                }
346 319
                if( column.isGeometry() ) {
347 320
                    String sql;
348 321
                    String constraint_name = "constraint_" + this.table().getName() + "_" + column.getName()+"_dim";
......
519 492
    }
520 493
    
521 494
    public H2SpatialHelper getHelper() {
522
        return this.helper;
495
        return (H2SpatialHelper) this.helper;
523 496
    }
497
    
498
    @Override
524 499
    public Disposable setStatementParameters(
525 500
        PreparedStatement st, 
526 501
        List values, 
......
576 551
                        }
577 552
                        break;
578 553
                    case DataTypes.GEOMETRY:
579
                        Geometry geom = this.getHelper().forceGeometryType(
554
                        Geometry geom = this.forceGeometryType(
580 555
                            descriptor.getGeomType(),
581 556
                            (Geometry)(feature.get(name))
582 557
                        );
......
620 595
        return new H2SpatialSelectBuilderBase();
621 596
    }
622 597

  
598
    @Override
599
    protected CreateIndexBuilder createCreateIndexBuilder() {
600
        return new H2SpatialCreateIndexBuilder();
601
    }
602

  
623 603
}
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.db/org.gvsig.fmap.dal.db.h2/src/main/java/org/gvsig/fmap/dal/store/h2/operations/H2SpatialFetchFeatureTypeOperation.java
17 17
import org.gvsig.fmap.dal.feature.EditableFeatureType;
18 18
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
19 19
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
20
import org.gvsig.fmap.dal.store.jdbc2.spi.SRSSolver;
20 21
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.FetchFeatureTypeOperation;
21 22
import org.gvsig.fmap.geom.Geometry;
22 23
import org.gvsig.fmap.geom.GeometryLocator;
......
142 143
            ResultSetMetaData rsMetadata,
143 144
            int colIndex
144 145
        ) {
145
        if( attr.getType()==DataTypes.GEOMETRY ) {
146
            GeometryColumnInfo column_info = this.geometry_column.get(attr.getName());
147
            String type = "GEOMETRY";
148
            if( column_info!=null ) {
149
                // H2GIS solo soporte 2D y 3D no soporta Ms
150
                if( column_info.dimensions==3 ) {
151
                    type = column_info.geometryTypeName+"Z";
152
                } else {
153
                    type = column_info.geometryTypeName;
146
        try {
147
            if( attr.getType()==DataTypes.GEOMETRY ) {
148
                GeometryColumnInfo column_info = this.geometry_column.get(attr.getName());
149
                String type = "GEOMETRY";
150
                if( column_info!=null ) {
151
                    // H2GIS solo soporte 2D y 3D no soporta Ms
152
                    if( column_info.dimensions==3 ) {
153
                        type = column_info.geometryTypeName+"Z";
154
                    } else {
155
                        type = column_info.geometryTypeName;
156
                    }
157
                    SRSSolver solver = this.helper.getSRSSolver();
158
                    attr.setSRS(
159
                        solver.getProjection(getConnection(), column_info.srid)
160
                    );
154 161
                }
155
                attr.setSRS(
156
                    this.helper.getProjectionFromDatabaseCode(
157
                        String.valueOf(column_info.srid)
158
                    )
159
                );
162
                GeometryType gt = getGeometryTypeFromH2SpatialType(type);
163
                if( gt != null ) {
164
                    attr.setGeometryType(gt);
165
                }
160 166
            }
161
            GeometryType gt = getGeometryTypeFromH2SpatialType(type);
162
            if( gt != null ) {
163
                attr.setGeometryType(gt);
164
            }
167
        } catch(Exception ex) {
168
            throw new RuntimeException("Can't fetch geometry type and SRS.", ex);
165 169
        }
166 170
    }
167 171

  
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.db/org.gvsig.fmap.dal.db.h2/src/main/java/org/gvsig/fmap/dal/store/h2/H2SpatialHelper.java
27 27
import org.apache.commons.dbcp.BasicDataSource;
28 28
import org.apache.commons.io.FilenameUtils;
29 29
import org.apache.commons.lang3.StringUtils;
30
import org.cresques.cts.IProjection;
31 30
import org.gvsig.fmap.dal.SQLBuilder;
32 31
import org.gvsig.fmap.dal.resource.exception.AccessResourceException;
33 32
import org.gvsig.fmap.dal.store.h2.operations.H2SpatialOperationsFactory;
......
40 39
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCHelperBase;
41 40
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
42 41
import org.gvsig.fmap.dal.store.jdbc2.spi.SRSSolverBase;
43
import org.gvsig.fmap.geom.Geometry;
44
import org.gvsig.fmap.geom.aggregate.MultiLine;
45
import org.gvsig.fmap.geom.aggregate.MultiPoint;
46
import org.gvsig.fmap.geom.aggregate.MultiPolygon;
47
import org.gvsig.fmap.geom.exception.CreateGeometryException;
48
import org.gvsig.fmap.geom.primitive.Primitive;
49
import org.gvsig.fmap.geom.type.GeometryType;
50 42
import org.h2gis.ext.H2GISExtension;
51 43
import org.slf4j.Logger;
52 44
import org.slf4j.LoggerFactory;
......
324 316
    }
325 317

  
326 318
    @Override
327
    public int getSRSCode(IProjection crs) {
328
        // TODO: ir a buscarlo a la BBDD a ver donde puede estar
329
        return super.getSRSCode(crs);
330
    }
331
    
332
    @Override
333
    public IProjection getProjectionFromSRSId(int srsid) {
334
        // TODO: ir a buscarlo a la BBDD a ver donde puede estar
335
        return super.getProjectionFromSRSId(srsid);
336
    }
337

  
338
    @Override
339 319
    public String getSourceId(JDBCStoreParameters parameters) {
340 320
        return parameters.getDBName() + "." + 
341 321
               parameters.getSchema()+ "." + 
......
357 337
        return new H2SpatialExplorerParameters();
358 338
    }
359 339

  
360
    public Geometry forceGeometryType(GeometryType geomtype, Geometry geom) throws CreateGeometryException {
361
        if( geom == null ) {
362
            return geom;
363
        }
364
        switch( geomtype.getType() ) {
365
        case Geometry.TYPES.MULTIPOLYGON:
366
            if( geom.getType()==Geometry.TYPES.POLYGON ) {
367
                MultiPolygon x = getGeometryManager().createMultiPolygon(geomtype.getSubType());
368
                x.addPrimitive((Primitive) geom);
369
                geom = x;
370
            }
371
            break;
372
        case Geometry.TYPES.MULTILINE:
373
            if( geom.getType()==Geometry.TYPES.LINE ) {
374
                MultiLine x = getGeometryManager().createMultiLine(geomtype.getSubType());
375
                x.addPrimitive((Primitive) geom);
376
                geom = x;
377
            }
378
            break;
379
        case Geometry.TYPES.MULTIPOINT:
380
            if( geom.getType()==Geometry.TYPES.POINT ) {
381
                MultiLine x = getGeometryManager().createMultiLine(geomtype.getSubType());
382
                x.addPrimitive((Primitive) geom);
383
                geom = x;
384
            }
385
            break;
386
        case Geometry.TYPES.POLYGON:
387
            if( geom.getType()==Geometry.TYPES.MULTIPOLYGON ) {
388
                MultiPolygon x = (MultiPolygon) geom;
389
                if( x.getPrimitivesNumber()==1 ) {
390
                    geom = x.getPrimitiveAt(0);
391
                }
392
            }
393
            break;
394
        case Geometry.TYPES.LINE:
395
            if( geom.getType()==Geometry.TYPES.MULTILINE ) {
396
                MultiLine x = (MultiLine) geom;
397
                if( x.getPrimitivesNumber()==1 ) {
398
                    geom = x.getPrimitiveAt(0);
399
                }
400
            }
401
            break;
402
        case Geometry.TYPES.POINT:
403
            if( geom.getType()==Geometry.TYPES.MULTIPOINT ) {
404
                MultiPoint x = (MultiPoint) geom;
405
                if( x.getPrimitivesNumber()==1 ) {
406
                    geom = x.getPrimitiveAt(0);
407
                }
408
            }
409
        }
410
        return geom;
411
    }
412
    
413 340
}
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.db/org.gvsig.fmap.dal.db.jdbc/src/main/java/org/gvsig/fmap/dal/store/jdbc2/JDBCHelper.java
3 3
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
4 4
import java.sql.Connection;
5 5
import java.sql.ResultSet;
6
import org.cresques.cts.IProjection;
7 6
import org.gvsig.fmap.dal.exception.DataException;
8 7
import org.gvsig.fmap.dal.exception.InitializeException;
9 8
import org.gvsig.fmap.dal.ExpressionBuilder.GeometrySupportType;
......
165 164

  
166 165
    public SRSSolver getSRSSolver();
167 166
    
168
    public String getDatabaseCodeFromProyection(IProjection proj);
169
    
170
    public IProjection getProjectionFromDatabaseCode(String databaseCode);
171
    
172
    /**
173
     * @param crs
174
     * @return 
175
     * @deprecated use getDatabaseCodeFromProyection
176
     */
177
    public int getSRSCode(IProjection crs);
178
    
179
    /**
180
     * @param srsid
181
     * @return 
182
     * @deprecated use getProjectionFromDatabaseCode
183
     */
184
    public IProjection getProjectionFromSRSId(int srsid);
185

  
186 167
    public JDBCNewStoreParameters createNewStoreParameters();
187 168

  
188 169
    public JDBCStoreParameters createOpenStoreParameters();
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.db/org.gvsig.fmap.dal.db.jdbc/src/main/java/org/gvsig/fmap/dal/store/jdbc2/spi/SRSSolverDumb.java
20 20
        }
21 21
    }
22 22

  
23
    @Override
24 23
    protected String searchApplicationAbbrev(Connection connection, String databaseCode) {
25 24
        try {
26 25
            return "EPSG:" + databaseCode.trim();
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.db/org.gvsig.fmap.dal.db.jdbc/src/main/java/org/gvsig/fmap/dal/store/jdbc2/spi/JDBCHelperBase.java
5 5
import java.sql.Connection;
6 6
import java.sql.ResultSet;
7 7
import org.apache.commons.lang3.StringUtils;
8
import org.cresques.cts.IProjection;
9
import org.gvsig.fmap.crs.CRSFactory;
10 8
import org.gvsig.fmap.dal.DataTypes;
11 9
import org.gvsig.fmap.dal.exception.DataException;
12 10
import org.gvsig.fmap.dal.exception.InitializeException;
......
120 118

  
121 119
    @Override
122 120
    public JDBCSQLBuilderBase createSQLBuilder() {
123
        return new JDBCSQLBuilderBase();
121
        return new JDBCSQLBuilderBase(this);
124 122
    }
125 123

  
126 124
    @Override
......
337 335
        }
338 336
        return !StringUtils.isEmpty(this.store.getParameters().getSQL());
339 337
    }  
340

  
341
    @Override
342
    public int getSRSCode(IProjection crs) {
343
        Connection connection=null;
344
        try {
345
            connection = this.getConnection();
346
            String databaseCode = this.srssolver.getDatabaseCode(connection, crs.getAbrev());
347
            return Integer.parseInt(databaseCode);
348
        } catch(Throwable ex) {
349
            throw new RuntimeException(ex);
350
        } finally {
351
            this.closeConnection(connection);
352
        }
353
    }
354

  
355
    @Override
356
    public IProjection getProjectionFromSRSId(int srsid) {
357
        return getProjectionFromDatabaseCode(String.valueOf(srsid));
358
    }
359

  
360
    @Override
361
    public String getDatabaseCodeFromProyection(IProjection proj) {
362
        Connection connection=null;
363
        try {
364
            connection = this.getConnection();
365
            return this.srssolver.getDatabaseCode(connection, proj);
366
        } catch(Throwable ex) {
367
            throw new RuntimeException(ex);
368
        } finally {
369
            this.closeConnection(connection);
370
        }
371
    }
372 338
    
373 339
    @Override
374 340
    public SRSSolver getSRSSolver() {
......
376 342
    }
377 343
    
378 344
    @Override
379
    public IProjection getProjectionFromDatabaseCode(String databaseCode) {
380
        Connection connection=null;
381
        try {
382
            connection = this.getConnection();
383
            return this.srssolver.getProjection(connection, databaseCode);
384
        } catch(Throwable ex) {
385
            throw new RuntimeException(ex);
386
        } finally {
387
            this.closeConnection(connection);
388
        }
389
    }
390
    
391
    @Override
392 345
    public JDBCStoreProvider createProvider(
393 346
            JDBCStoreParameters parameters, 
394 347
            DataStoreProviderServices providerServices
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.db/org.gvsig.fmap.dal.db.jdbc/src/main/java/org/gvsig/fmap/dal/store/jdbc2/spi/SRSSolverBase.java
11 11
import org.gvsig.fmap.crs.CRSFactory;
12 12
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
13 13
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
14
import org.slf4j.Logger;
15
import org.slf4j.LoggerFactory;
14 16

  
15 17
public class SRSSolverBase implements SRSSolver {
18
    protected static final Logger logger = LoggerFactory.getLogger(SRSSolverBase.class);
16 19
    
17
    protected Map<String,String> database2applicationAbbrev;
18
    protected Map<String,String> applicationAbbrev2database;
20
    protected Map<Object,String> database2applicationAbbrev;
21
    protected Map<String,Object> applicationAbbrev2database;
19 22
    protected JDBCHelper helper;
20 23
    
21 24
    public SRSSolverBase(JDBCHelper helper) {
......
25 28
    }
26 29
    
27 30
    @Override
28
    public void add(String databaseCode, String applicationAbbrev) {
31
    public void add(Object databaseCode, String applicationAbbrev) {
29 32
        this.applicationAbbrev2database.put(applicationAbbrev, databaseCode);
30 33
        this.database2applicationAbbrev.put(databaseCode, applicationAbbrev);
31 34
    }
32 35
    
33 36
    @Override
34
    public String getDatabaseCode(Connection connection, String applicationAbbrev) {
37
    public Object getDatabaseCode(Connection connection, String applicationAbbrev) {
35 38
        if( this.hasApplicationAbbrev(connection, applicationAbbrev) ) {
36 39
            return this.applicationAbbrev2database.get(applicationAbbrev);
37 40
        }
38
        String databaseCode = this.searchDatabaseCode(connection, applicationAbbrev);
39
        if( StringUtils.isEmpty(databaseCode) ) {
41
        Object databaseCode = this.searchDatabaseCode(connection, applicationAbbrev);
42
        if( databaseCode==null ) {
40 43
            return null;
41 44
        }
45
        if( databaseCode instanceof String && StringUtils.isEmpty((String)databaseCode) ) {
46
            return null;
47
        }
42 48
        this.add(databaseCode, applicationAbbrev);
43 49
        return databaseCode;
44 50
    }
45 51
    
46 52
    @Override
47
    public String getApplicationAbbrev(Connection connection, String databaseCode) {
53
    public String getApplicationAbbrev(Connection connection, Object databaseCode) {
48 54
        if( this.hasDatabaseCode(connection, databaseCode) ) {
49 55
            return this.database2applicationAbbrev.get(databaseCode);
50 56
        }
......
57 63
    }
58 64
    
59 65
    @Override
60
    public boolean hasDatabaseCode(Connection connection, String databaseCode) {
66
    public boolean hasDatabaseCode(Connection connection, Object databaseCode) {
61 67
        return this.database2applicationAbbrev.containsKey(databaseCode);
62 68
    }
63 69
    
......
66 72
        return this.applicationAbbrev2database.containsKey(applicationAbbrev);
67 73
    }
68 74

  
69
    protected String searchDatabaseCode(Connection connection, String applicationAbbrev) {
75
    protected Object searchDatabaseCode(Connection connection, String applicationAbbrev) {
70 76
        // Initialize sql only for debugging purposes
71 77
        String sql = "select srid, auth_name, auth_srid from spatial_ref_sys where auth_name/auth_srid is '"+applicationAbbrev+"'.";
72 78
        try {
73
            String[] s = applicationAbbrev.split(applicationAbbrev);
79
            String[] s = applicationAbbrev.split(":");
74 80
            sql = "select srid, auth_name, auth_srid from spatial_ref_sys where auth_name = '" + s[0] +"' and auth_srid = '"+s[1]+"' ";
75 81
            Statement st = connection.createStatement();
76 82
            ResultSet rs = JDBCUtils.executeQuery(st, sql);
77 83
            if ( rs.next() ) {
78 84
                int srid = rs.getInt("srid");
79
                return String.valueOf(srid);
85
                return srid;
80 86
            }            
81 87
            return null;
82 88
        } catch (Throwable ex) {
83
            throw new RuntimeException("Problems with SQL '"+sql+"'.",ex);
89
            logger.warn("Can't retrieve SRS code from spatial_ref_sys ("+sql+").", ex);
90
            throw new RuntimeException("Can't retrieve SRS code from spatial_ref_sys ("+sql+").",ex);
84 91
        }
85 92
    }
86 93

  
87
    protected String searchApplicationAbbrev(Connection connection, String databaseCode) {
94
    protected String searchApplicationAbbrev(Connection connection, Object databaseCode) {
88 95
        String sql = "select srid, auth_name, auth_srid from spatial_ref_sys where srid = " + databaseCode;
89 96
        try {
90 97
            Statement st = connection.createStatement();
......
96 103
            }            
97 104
            return null;
98 105
        } catch (Throwable ex) {
99
            throw new RuntimeException("Problems with SQL '"+sql+"'.",ex);
106
            logger.warn("Can't retrieve SRS from spatial_ref_sys ("+sql+").", ex);
107
            throw new RuntimeException("Can't retrieve SRS from spatial_ref_sys ("+sql+").",ex);
100 108
        }
101 109
    }
102 110

  
103 111
    @Override
104
    public IProjection getProjection(Connection connection, String databaseCode) {
105
        if( StringUtils.trimToEmpty(databaseCode).equals("0") ) {
112
    public IProjection getProjection(Connection connection, Object databaseCode) {
113
        if( databaseCode == null ) {
106 114
            return null;
107 115
        }
116
        String s = databaseCode.toString().trim();
117
        if( s.equals("0") ) {
118
            return null;
119
        }
108 120
        String abbrev = this.getApplicationAbbrev(connection, databaseCode);
109 121
        if( StringUtils.isEmpty(abbrev) ) {
110 122
            return null;
......
114 126
    }
115 127

  
116 128
    @Override
117
    public String getDatabaseCode(Connection connection, IProjection projection) {
129
    public Object getDatabaseCode(Connection connection, IProjection projection) {
118 130
        return this.getDatabaseCode(connection, projection.getAbrev());
119 131
    }
120 132

  
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.db/org.gvsig.fmap.dal.db.jdbc/src/main/java/org/gvsig/fmap/dal/store/jdbc2/spi/SRSSolver.java
6 6

  
7 7
public interface SRSSolver {
8 8

  
9
    void add(String databaseCode, String applicationAbbrev);
9
    void add(Object databaseCode, String applicationAbbrev);
10 10

  
11
    String getApplicationAbbrev(Connection connection, String databaseCode);
11
    String getApplicationAbbrev(Connection connection, Object databaseCode);
12 12

  
13
    String getDatabaseCode(Connection connection, String applicationAbbrev);
13
    Object getDatabaseCode(Connection connection, String applicationAbbrev);
14 14

  
15 15
    boolean hasApplicationAbbrev(Connection connection, String applicationAbbrev);
16 16

  
17
    boolean hasDatabaseCode(Connection connection, String databaseCode);
17
    boolean hasDatabaseCode(Connection connection, Object databaseCode);
18 18

  
19
    public IProjection getProjection(Connection connection, String databaseCode);
19
    public IProjection getProjection(Connection connection, Object databaseCode);
20 20
    
21
    public String getDatabaseCode(Connection connection, IProjection projection);
21
    public Object getDatabaseCode(Connection connection, IProjection projection);
22 22
}
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.db/org.gvsig.fmap.dal.db.jdbc/src/main/java/org/gvsig/fmap/dal/store/jdbc2/spi/operations/PerformChangesOperation.java
4 4
import java.sql.PreparedStatement;
5 5
import java.sql.SQLException;
6 6
import java.sql.Statement;
7
import java.util.ArrayList;
7 8
import java.util.Iterator;
9
import java.util.List;
10
import org.apache.commons.collections.CollectionUtils;
8 11
import org.apache.commons.lang3.StringUtils;
9 12
import org.gvsig.fmap.dal.DataTypes;
10 13
import org.gvsig.fmap.dal.exception.DataException;
......
14 17
import org.gvsig.fmap.dal.feature.spi.FeatureProvider;
15 18
import org.gvsig.fmap.dal.feature.spi.FeatureReferenceProviderServices;
16 19
import org.gvsig.fmap.dal.feature.spi.FeatureStoreProvider;
17
import org.gvsig.fmap.dal.feature.spi.SQLBuilderBase;
18 20
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
19 21
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecuteSQLException;
20 22
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
......
276 278
        }
277 279
    }
278 280

  
279
    protected JDBCSQLBuilderBase buildUpdateTableSQL(
281
    protected List<String> buildUpdateTableSQL(
280 282
            String database,
281 283
            String schema,
282 284
            String table,
......
343 345
                }
344 346
            }
345 347
        }
346
        return sqlbuilder;
348
        return sqlbuilder.alter_table().toStrings();
347 349
    }
348 350
    
349 351
    protected boolean areEquals(FeatureAttributeDescriptor attr1, FeatureAttributeDescriptor attr2) {
......
364 366
        if( attr1.isPrimaryKey() != attr2.isPrimaryKey() ) {
365 367
            return false;
366 368
        }        
367
        if( attr1.isIndexed() != attr2.isIndexed() ) {
368
            return false;
369
        }
369
//        if( attr1.isIndexed() != attr2.isIndexed() ) {
370
//            return false;
371
//        }
370 372
        if( attr1.allowNull() != attr2.allowNull() ) {
371 373
            return false;
372 374
        }
......
384 386
        return true;
385 387
    }
386 388

  
389
    protected List<String> buildCreateIndexSQL(
390
            String database,
391
            String schema,
392
            String table,
393
            FeatureType original,
394
            FeatureType target
395
        ) {
396
        ArrayList<String> sqls = new ArrayList<>();
397
        
398
        for (FeatureAttributeDescriptor attrTarget : target) {
399
            boolean createIndex = false;
400
            if( attrTarget.isIndexed() ) {
401
                FeatureAttributeDescriptor attrOriginal = original.getAttributeDescriptor(attrTarget.getName());
402
                if ( attrOriginal == null) {
403
                    createIndex = true;
404
                } else {
405
                    if( attrOriginal.isIndexed() ) {
406
                        createIndex = false;
407
                    } else {
408
                        createIndex = true;
409
                    }
410
                }
411
            }
412
            if( createIndex ) {
413
                JDBCSQLBuilderBase sqlbuilder = createSQLBuilder();
414
                if( attrTarget.getType()==DataTypes.GEOMETRY ) {
415
                    sqlbuilder.create_index().spatial();
416
                }
417
                sqlbuilder.create_index().if_not_exist();
418
                sqlbuilder.create_index().name("idx_" + table + "_" + attrTarget.getName());
419
                sqlbuilder.create_index().column(attrTarget.getName());
420
                sqlbuilder.create_index().table().database(database).schema(schema).name(table);
421
                sqls.addAll(sqlbuilder.create_index().toStrings());
422
            }
423
        }
424
        return sqls;
425
    }
426
    
387 427
    public void performUpdateTable(Connection conn,
388 428
            String database,
389 429
            String schema,
390 430
            String table,
391 431
            FeatureType original,
392 432
            FeatureType target) throws DataException {
393
        SQLBuilderBase sqlbuilder = buildUpdateTableSQL(database, schema, table, original, target);
394
        Statement st = null;
395
        try {
396
            st = conn.createStatement();
397
            for (String sql : sqlbuilder.alter_table().toStrings()) {
398
                JDBCUtils.execute(st, sql);
433
        
434
        ArrayList<String> sqls = new ArrayList<>();
435
        
436
        sqls.addAll(buildUpdateTableSQL(database, schema, table, original, target));
437
        sqls.addAll(buildCreateIndexSQL(database, schema, table, original, target));
438

  
439
        if( !CollectionUtils.isEmpty(sqls) ) {
440
            Statement st = null;
441
            try {
442
                st = conn.createStatement();
443
                for (String sql : sqls) {
444
                    JDBCUtils.execute(st, sql);
445
                }
446
            } catch (SQLException e) {
447
                throw new JDBCSQLException(e);
448
            } finally {
449
                JDBCUtils.closeQuietly(st);
399 450
            }
400
        } catch (SQLException e) {
401
            throw new JDBCSQLException(e);
402
        } finally {
403
            JDBCUtils.closeQuietly(st);
404 451
        }
405 452
    }
406

  
407 453
}
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.db/org.gvsig.fmap.dal.db.jdbc/src/main/java/org/gvsig/fmap/dal/store/jdbc2/spi/operations/CreateTableOperation.java
3 3
import java.sql.Connection;
4 4
import java.sql.SQLException;
5 5
import java.sql.Statement;
6
import java.util.ArrayList;
6 7
import java.util.List;
8
import org.apache.commons.collections.CollectionUtils;
7 9
import org.apache.commons.lang3.tuple.Pair;
8 10
import org.gvsig.fmap.dal.exception.DataException;
9 11
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
......
55 57
                type, userAndPrivileges, additionalSQLs);
56 58
    }
57 59

  
60
    protected List<String> buildCreateIndexesSQL(
61
            String database,
62
            String schema,
63
            String table,
64
            FeatureType type
65
        ) {
66
        ArrayList<String> sqls = new ArrayList<>();
67
        
68
        for (FeatureAttributeDescriptor attr : type) {
69
            if( attr.isIndexed() ) {
70
                JDBCSQLBuilderBase sqlbuilder = createSQLBuilder();
71
                if( attr.getType()==org.gvsig.fmap.dal.DataTypes.GEOMETRY ) {
72
                    sqlbuilder.create_index().spatial();
73
                }
74
                sqlbuilder.create_index().if_not_exist();
75
                sqlbuilder.create_index().name("idx_" + table + "_" + attr.getName());
76
                sqlbuilder.create_index().column(attr.getName());
77
                sqlbuilder.create_index().table().database(database).schema(schema).name(table);
78
                sqls.addAll(sqlbuilder.create_index().toStrings());
79
            }
80
        }
81
        return sqls;
82
    }
83
    
58 84
    public boolean performCreateTable(Connection conn,
59 85
            String dbName, 
60 86
            String schemaName,
......
95 121

  
96 122
        List<String> sqls;
97 123
        sqls = sqlbuilder.create_table().toStrings();
124
        sqls.addAll(buildCreateIndexesSQL(dbName, schemaName, tableName, type));
98 125
        sqls.addAll(sqlbuilder.grant().toStrings());
99 126
        sqls.addAll(additionalSQLs);
100 127

  
......
102 129
        try {
103 130
            st = conn.createStatement();
104 131
            for (String sql : sqls) {
105
                
106 132
                JDBCUtils.execute(st, sql);
107 133
            }
108 134
        } catch (SQLException ex) {
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.db/org.gvsig.fmap.dal.db.jdbc/src/main/java/org/gvsig/fmap/dal/store/jdbc2/spi/JDBCSQLBuilderBase.java
1 1
package org.gvsig.fmap.dal.store.jdbc2.spi;
2 2

  
3
import java.sql.Connection;
3 4
import java.sql.PreparedStatement;
4 5
import java.sql.SQLException;
5 6
import java.util.ArrayList;
6 7
import java.util.List;
8
import org.cresques.cts.IProjection;
9
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
7 10
import org.gvsig.fmap.dal.feature.FeatureReference;
11
import org.gvsig.fmap.dal.feature.FeatureType;
8 12
import org.gvsig.fmap.dal.feature.spi.SQLBuilderBase;
9 13
import org.gvsig.fmap.dal.feature.spi.FeatureProvider;
10 14
import org.gvsig.fmap.dal.feature.spi.FeatureReferenceProviderServices;
15
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
16
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
17
import org.gvsig.fmap.geom.DataTypes;
11 18
import org.gvsig.fmap.geom.Geometry;
19
import org.gvsig.fmap.geom.GeometryLocator;
20
import org.gvsig.fmap.geom.GeometryManager;
21
import org.gvsig.fmap.geom.aggregate.MultiLine;
22
import org.gvsig.fmap.geom.aggregate.MultiPoint;
23
import org.gvsig.fmap.geom.aggregate.MultiPolygon;
24
import org.gvsig.fmap.geom.exception.CreateGeometryException;
25
import org.gvsig.fmap.geom.primitive.Primitive;
26
import org.gvsig.fmap.geom.type.GeometryType;
12 27
import org.gvsig.tools.dispose.Disposable;
13 28

  
14 29
public class JDBCSQLBuilderBase extends SQLBuilderBase {
15 30

  
16
    public JDBCSQLBuilderBase() {
31
    private GeometryManager geometryManager = null;
32
    protected final JDBCHelper helper;
33
    
34
    public JDBCSQLBuilderBase(JDBCHelper helper) {
17 35
        super();
36
        this.helper = helper;
18 37
    }
19

  
38
    
39
    public JDBCHelper getHelper() {
40
        return helper;
41
    }
42
    
43
    protected GeometryManager getGeometryManager() {
44
        if (this.geometryManager == null) {
45
            this.geometryManager = GeometryLocator.getGeometryManager();
46
        }
47
        return this.geometryManager;
48
    }
49
    
50
    @Override
51
    public Object getSRSId(IProjection projection) {
52
        Connection conn = null;
53
        try {
54
            conn = this.helper.getConnection();
55
            SRSSolver solver = this.helper.getSRSSolver();
56
            Object srscode = solver.getDatabaseCode(conn, projection);
57
            return srscode;
58
        } catch (Exception ex) {
59
            throw new RuntimeException("Can't locate database code for SRS '"+projection.getAbrev()+"'.");
60
        } finally {
61
            JDBCUtils.closeQuietly(conn);
62
        }
63
    }
64
    
20 65
    public void setParameters(PreparedStatement st) {
21 66
        try {
22 67
            int columnIndex = 1;
......
36 81

  
37 82
    public Disposable setParameters(PreparedStatement st, FeatureProvider feature) {
38 83
        try {
84
            FeatureType type = feature.getType();
39 85
            List<Object> values = new ArrayList<>();
86
            Object value;
40 87
            for (Parameter parameter : this.getParameters()) {
41 88
                if (parameter.is_constant()) {
42
                    values.add(parameter.getValue());
89
                    value = parameter.getValue();
90
                    values.add(value);
43 91
                } else {
44 92
                    String name = parameter.getName();
45
                    values.add(feature.get(name));
93
                    value = feature.get(name);
94
                    FeatureAttributeDescriptor attrDesc = type.getAttributeDescriptor(name);
95
                    if( attrDesc.getType()==DataTypes.GEOMETRY ) {
96
                        value = forceGeometryType(attrDesc.getGeomType(), (Geometry) value);                        
97
                    }
98
                    values.add(value);
46 99
                }
47 100
            }
48 101
            return this.setStatementParameters(st, values, this.geometry_support_type());
......
56 109
            throw new RuntimeException("Can't set parameters to prepared statement from the feature (" + f + ")", ex);
57 110
        }
58 111
    }
59

  
112
    
113
    protected Geometry forceGeometryType(GeometryType geomtype, Geometry geom) throws CreateGeometryException {
114
        if( geom == null ) {
115
            return null;
116
        }
117
        switch( geomtype.getType() ) {
118
        case Geometry.TYPES.MULTIPOLYGON:
119
            if( geom.getType()==Geometry.TYPES.POLYGON ) {
120
                MultiPolygon x = getGeometryManager().createMultiPolygon(geomtype.getSubType());
121
                x.addPrimitive((Primitive) geom);
122
                geom = x;
123
            }
124
            break;
125
        case Geometry.TYPES.MULTILINE:
126
            if( geom.getType()==Geometry.TYPES.LINE ) {
127
                MultiLine x = getGeometryManager().createMultiLine(geomtype.getSubType());
128
                x.addPrimitive((Primitive) geom);
129
                geom = x;
130
            }
131
            break;
132
        case Geometry.TYPES.MULTIPOINT:
133
            if( geom.getType()==Geometry.TYPES.POINT ) {
134
                MultiLine x = getGeometryManager().createMultiLine(geomtype.getSubType());
135
                x.addPrimitive((Primitive) geom);
136
                geom = x;
137
            }
138
            break;
139
        case Geometry.TYPES.POLYGON:
140
            if( geom.getType()==Geometry.TYPES.MULTIPOLYGON ) {
141
                MultiPolygon x = (MultiPolygon) geom;
142
                if( x.getPrimitivesNumber()==1 ) {
143
                    geom = x.getPrimitiveAt(0);
144
                }
145
            }
146
            break;
147
        case Geometry.TYPES.LINE:
148
            if( geom.getType()==Geometry.TYPES.MULTILINE ) {
149
                MultiLine x = (MultiLine) geom;
150
                if( x.getPrimitivesNumber()==1 ) {
151
                    geom = x.getPrimitiveAt(0);
152
                }
153
            }
154
            break;
155
        case Geometry.TYPES.POINT:
156
            if( geom.getType()==Geometry.TYPES.MULTIPOINT ) {
157
                MultiPoint x = (MultiPoint) geom;
158
                if( x.getPrimitivesNumber()==1 ) {
159
                    geom = x.getPrimitiveAt(0);
160
                }
161
            }
162
        }
163
        return geom;
164
    }
165
    
60 166
    public Disposable setParameters(PreparedStatement st, FeatureReference reference) {
61 167
        try {
62 168
            
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.api/src/main/java/org/gvsig/fmap/dal/ExpressionBuilder.java
175 175

  
176 176
    public String string(String s);
177 177
   
178
    public int getSRSId(IProjection projection);
178
    public Object getSRSId(IProjection projection);
179 179
    
180 180
    public Config getConfig();
181 181

  
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.api/src/main/java/org/gvsig/fmap/dal/SQLBuilder.java
63 63
        public final static String UPDATE_table_SET_columnsAndValues_WHERE_expresion = "UPDATE_table_SET_columnsAndValues_WHERE_expresion";
64 64
        public final static String UPDATE_table_SET_columnsAndValues = "UPDATE_table_SET_columnsAndValues";
65 65
        public final static String GRANT_privileges_ON_table_TO_role = "GRANT_privileges_ON_table_TO_role";
66
        public final static String CREATE_INDEX_name_ON_table_column = "CREATE_INDEX_name_ON_table_column";
67
        public final static String CREATE_INDEX_name_ON_table_USING_GIST_column = "CREATE_INDEX_name_ON_table_USING_GIST_column";
66
//        public final static String CREATE_INDEX_name_ON_table_column = "CREATE_INDEX_name_ON_table_column";
67
//        public final static String CREATE_INDEX_name_ON_table_USING_GIST_column = "CREATE_INDEX_name_ON_table_USING_GIST_column";
68 68
   
69 69
    }
70 70
    
......
91 91
        public Object getDefaultValue();
92 92
        public int getGeometryType();
93 93
        public int getGeometrySubtype();
94
        public int getGeometrySRSId();
94
        public Object getGeometrySRSId();
95 95
        public boolean isGeometry();
96 96
        
97 97
        public void setName(String name);
......
104 104
        public void setDefaultValue(Object defaultValue);
105 105
        public void setGeometryType(int geom_type);
106 106
        public void setGeometrySubtype(int geom_subtype);
107
        public void setGeometrySRSId(int geom_srsid);
107
        public void setGeometrySRSId(Object geom_srsid);
108 108
    }
109 109

  
110 110
    public interface CountBuilder extends Value {
......
218 218
        public AlterTableBuilder drop_column(String columnName);
219 219
        public AlterTableBuilder add_column(String columnName, int type, int type_p, int type_s, boolean isPk, boolean isIndexed, boolean allowNulls, boolean isAutomatic, Object defaultValue);
220 220
        public AlterTableBuilder add_geometry_column(String columnName, int geom_type, int geom_subtype, IProjection proj, boolean isIndexed, boolean allowNulls);
221
        public AlterTableBuilder add_geometry_column(String columnName, int geom_type, int geom_subtype, Object srsdbcode, boolean isIndexed, boolean allowNulls);
221 222
        public AlterTableBuilder alter_column(String columnName, int type, int type_p, int type_s, boolean isPk, boolean isIndexed, boolean allowNulls, boolean isAutomatic, Object defaultValue);
222 223
        public AlterTableBuilder alter_geometry_column(String columnName, int geom_type, int geom_subtype, IProjection proj, boolean isIndexed, boolean allowNulls);
224
        public AlterTableBuilder alter_geometry_column(String columnName, int geom_type, int geom_subtype, Object srsdbcode, boolean isIndexed, boolean allowNulls);
223 225
        public AlterTableBuilder rename_column(String source, String target);
226
        public boolean isEmpty();
224 227
        public List<String> toStrings();
225 228
    }
226 229
    
......
228 231
        public TableNameBuilder table();
229 232
        public CreateTableBuilder add_column(String columnName, int type, int type_p, int type_s, boolean isPk, boolean isIndexed, boolean allowNulls, boolean isAutomatic, Object defaultValue);
230 233
        public CreateTableBuilder add_geometry_column(String columnName, int geom_type, int geom_subtype, IProjection proj, boolean isIndexed, boolean allowNulls);
234
        public CreateTableBuilder add_geometry_column(String columnName, int geom_type, int geom_subtype, Object srsdbcode, boolean isIndexed, boolean allowNulls);
231 235
        public ColumnDescriptorBuilder getColumnDescriptor(String columnName);
232 236
        public List<String> toStrings();
233 237
    }
......
259 263
        public TableNameBuilder table();
260 264
        public List<String> toStrings();
261 265
    }
266
    
267
    public interface CreateIndexBuilder extends Statement {
268
        public CreateIndexBuilder if_not_exist();
269
        public CreateIndexBuilder unique();
270
        public CreateIndexBuilder name(String name);
271
        public CreateIndexBuilder spatial();
272
        public CreateIndexBuilder column(String name);
273
        public TableNameBuilder table();
274
        public List<String> toStrings();
275
    }
262 276

  
263 277
    public String default_schema();
264 278
    
......
284 298
    public AlterTableBuilder alter_table();
285 299

  
286 300
    public CreateTableBuilder create_table();
301
    
302
    public CreateIndexBuilder create_index();
287 303

  
288 304
    public GrantBuilder grant();
289 305

  
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.api/src/main/java/org/gvsig/fmap/dal/feature/FeatureStoreProviderFactory.java
62 62
	 * in the generated stores' feature types.
63 63
	 */
64 64
	public boolean allowsMandatoryAttributes();
65
    
66
    public boolean preferNotToUseNonNullRestrictions();
65 67

  
66 68
	/**
67 69
	 *
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.spi/src/main/java/org/gvsig/fmap/dal/feature/spi/AbstractFeatureStoreProviderFactory.java
66 66
    public boolean allowsMandatoryAttributes() {
67 67
        return true;
68 68
    }
69
    
70
    public boolean preferNotToUseNonNullRestrictions() {
71
        return false;
72
    }
69 73

  
70 74
    public boolean allowsPrimaryKeyAttributes() {
71 75
        return true;
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.spi/src/main/java/org/gvsig/fmap/dal/feature/spi/ExpressionBuilderBase.java
761 761
    }
762 762
    
763 763
    @Override
764
    public int getSRSId(IProjection projection) {
764
    public Object getSRSId(IProjection projection) {
765 765
        String abrev = projection.getAbrev();
766
        return Integer.valueOf(abrev.split(":")[1]);
766
        return abrev.split(":")[1].trim();
767 767
    }
768 768

  
769 769
    @Override
......
793 793
        return parameter;
794 794
    }
795 795
    
796
    @Override
796 797
    public Parameter parameter() {
797 798
        return new ParameterBase();
798 799
    }
......
853 854

  
854 855
    private static class ParametersBase extends ArrayList<Parameter> implements Parameters {
855 856

  
857
        private static final long serialVersionUID = -2188534574151780470L;
858

  
856 859
        public ParametersBase() {
857 860
            super();
858 861
        }
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.spi/src/main/java/org/gvsig/fmap/dal/feature/spi/SQLBuilderBase.java
49 49
    protected GrantBuilder grant;
50 50
    protected DropTableBuilder drop_table;
51 51
    protected UpdateTableStatisticsBuilder update_table_statistics;
52
    protected CreateIndexBuilder create_index;
52 53
    protected List<Parameter> parameters;
53 54

  
54 55
    protected class ColumnDescriptorBuilderBase implements ColumnDescriptorBuilder {
......
63 64
        private Object defaultValue;
64 65
        private int geom_type;
65 66
        private int geom_subtype;
66
        private int geom_srsid;
67
        private Object geom_srsdbcode;
67 68
        private boolean _isIndexed;
68 69

  
69 70
        public ColumnDescriptorBuilderBase(String name, int type, Object defaultValue) {
......
77 78
            this.defaultValue = defaultValue;
78 79
            this.geom_type = Geometry.TYPES.GEOMETRY;
79 80
            this.geom_subtype = Geometry.SUBTYPES.GEOM2D;
80
            this.geom_srsid = -1;
81
            this.geom_srsdbcode = null;
81 82
            this._isIndexed = false;
82 83
        }
83 84

  
......
92 93
            this.defaultValue = defaultValue;
93 94
            this.geom_type = Geometry.TYPES.GEOMETRY;
94 95
            this.geom_subtype = Geometry.SUBTYPES.GEOM2D;
95
            this.geom_srsid = -1;
96
            this.geom_srsdbcode = null;
96 97
            this._isIndexed = isIndexed;
97 98
        }
98 99
        
......
107 108
            this.defaultValue = null;
108 109
            this.geom_type = geom_type;
109 110
            this.geom_subtype = geom_subtype;
110
            this.geom_srsid = getSRSId(proj);
111
            this.geom_srsdbcode = getSRSId(proj);
111 112
            this._isIndexed = isIndexed;
112 113
        }
113 114
        
115
        public ColumnDescriptorBuilderBase(String name, int geom_type, int geom_subtype, Object srsdbcode, boolean isIndexed, boolean allowNulls) {
116
            this.name = name;
117
            this.type = DataTypes.GEOMETRY;
118
            this.type_p = 0;
119
            this.type_s = 0;
120
            this.isPk = false;
121
            this._allowNulls = allowNulls;
122
            this._isAutomatic = false;
123
            this.defaultValue = null;
124
            this.geom_type = geom_type;
125
            this.geom_subtype = geom_subtype;
126
            this.geom_srsdbcode = srsdbcode;
127
            this._isIndexed = isIndexed;
128
        }
129
        
114 130
        @Override
115 131
        public String getName() {
116 132
            return this.name;
......
217 233
        }
218 234

  
219 235
        @Override
220
        public int getGeometrySRSId() {
221
            return geom_srsid;
236
        public Object getGeometrySRSId() {
237
            return geom_srsdbcode;
222 238
        }
223 239

  
224 240
        @Override
225
        public void setGeometrySRSId(int geom_srsid) {
226
            this.geom_srsid = geom_srsid;
241
        public void setGeometrySRSId(Object geom_srsid) {
242
            this.geom_srsdbcode = geom_srsid;
227 243
        }        
228 244

  
229 245
        @Override
......
1192 1208
        }
1193 1209
    }
1194 1210

  
1211
    public class CreateIndexBuilderBase implements CreateIndexBuilder {
1212

  
1213
        protected boolean ifNotExist = false;
1214
        protected boolean isUnique = false;
1215
        protected String indexName;
1216
        protected boolean isSpatial = false;
1217
        protected TableNameBuilder table;
1218
        protected final List<String> columns;
1219
        
1220
        public CreateIndexBuilderBase() {
1221
            this.columns = new ArrayList<>();
1222
        }
1223
        
1224
        @Override
1225
        public CreateIndexBuilder unique() {
1226
            this.isUnique = true;
1227
            return this;
1228
        }
1229

  
1230
        @Override
1231
        public CreateIndexBuilder if_not_exist() {
1232
            this.ifNotExist = true;
1233
            return this;
1234
        }
1235

  
1236
        @Override
1237
        public CreateIndexBuilder name(String name) {
1238
            this.indexName = name;
1239
            return this;
1240
        }
1241

  
1242
        @Override
1243
        public CreateIndexBuilder spatial() {
1244
            this.isSpatial = true;
1245
            return this;
1246
        }
1247

  
1248
        @Override
1249
        public CreateIndexBuilder column(String name) {
1250
            this.columns.add(name);
1251
            return this;
1252
        }
1253

  
1254
        @Override
1255
        public TableNameBuilder table() {
1256
            if( table == null ) {
1257
                table = createTableNameBuilder();
1258
            }
1259
            return table;
1260
        }
1261

  
1262
        @Override
1263
        public void accept(Visitor visitor, VisitorFilter filter) {
1264
            if( filter.accept(this) ) {
1265
                visitor.visit(this);
1266
            }
1267
            if( this.table != null ) {
1268
                this.table.accept(visitor, filter);
1269
            }
1270
        }
1271
        
1272
        @Override
1273
        public List<String> toStrings() {
1274
            StringBuilder builder = new StringBuilder();
1275
            builder.append("CREATE ");
1276
            if( this.isUnique ) {
1277
                builder.append("UNIQUE ");
1278
            }
1279
            builder.append("INDEX ");
1280
            if( this.ifNotExist ) {
1281
                builder.append("IF NOT EXISTS ");
1282
            }
1283
            builder.append(identifier(this.indexName));
1284
            builder.append(" ON ");
1285
            builder.append(this.table.toString());
1286
            if( this.isSpatial ) {
1287
                builder.append(" USING GIST ");
1288
            }
1289
            builder.append(" ( ");
1290
            boolean is_first_column = true;
1291
            for( String column : this.columns) {
1292
                if( is_first_column ) {
1293
                    is_first_column = false;
1294
                } else {
1295
                    builder.append(", ");
1296
                }
1297
                builder.append(column);
1298
            }
1299
            builder.append(" )");
1300
            
1301
            List<String> sqls = new ArrayList<>();
1302
            sqls.add(builder.toString());
1303
            return sqls;
1304
        }
1305

  
1306
    }
1307
    
1195 1308
    public class AlterTableBuilderBase implements AlterTableBuilder {
1196 1309

  
1197 1310
        protected TableNameBuilder table;
......
1208 1321
        }
1209 1322

  
1210 1323
        @Override
1324
        public boolean isEmpty() {
1325
            return this.drops.isEmpty() && 
1326
                this.adds.isEmpty() && 
1327
                this.alters.isEmpty() && 
1328
                this.renames.isEmpty();
1329
        }
1330
        
1331
        @Override
1211 1332
        public void accept(Visitor visitor, VisitorFilter filter) {
1212 1333
            if( filter.accept(this) ) {
1213 1334
                visitor.visit(this);
......
1250 1371
        }
1251 1372

  
1252 1373
        @Override
1374
        public AlterTableBuilder add_geometry_column(String columnName, int type, int subtype, Object srsdbcode, boolean isIndexed, boolean allowNulls) {
1375
            if( StringUtils.isEmpty(columnName) ) {
1376
                throw new IllegalArgumentException("Argument 'columnName' can't be empty.");
1377
            }
1378
            this.adds.add(new ColumnDescriptorBuilderBase(columnName, type, subtype, srsdbcode, isIndexed, allowNulls));
1379
            return this;
1380
        }
1381

  
1382
        @Override
1253 1383
        public AlterTableBuilder alter_column(String columnName, int type, int type_p, int type_s, boolean isPk, boolean isIndexed, boolean allowNulls, boolean isAutomatic, Object defaultValue) {
1254 1384
            if (isPk || isAutomatic) {
1255 1385
                allowNulls = false;
......
1268 1398
        }
1269 1399

  
1270 1400
        @Override
1401
        public AlterTableBuilder alter_geometry_column(String columnName, int type, int subtype, Object srsdbcode, boolean isIndexed, boolean allowNulls) {
1402
            if( StringUtils.isEmpty(columnName) ) {
1403
                throw new IllegalArgumentException("Argument 'columnName' can't be empty.");
1404
            }
1405
            this.alters.add(new ColumnDescriptorBuilderBase(columnName, type, subtype, srsdbcode, isIndexed, allowNulls));
1406
            return this;
1407
        }
1408

  
1409
        @Override
1271 1410
        public AlterTableBuilder rename_column(String source, String target) {
1272 1411
            this.renames.add(new ImmutablePair(source, target));
1273 1412
            return this;
......
1294 1433
        @Override
1295 1434
        public List<String> toStrings() {
1296 1435
            List<String> sqls = new ArrayList<>();
1297
            /*
1298
             ALTER TABLE [ ONLY ] name [ * ]
1299
             action [, ... ]
1300
             ALTER TABLE [ ONLY ] name [ * ]
1301
             RENAME [ COLUMN ] column TO new_column
1302
             ALTER TABLE name
1303
             RENAME TO new_name
1304
             ALTER TABLE name
1305
             SET SCHEMA new_schema
1306

  
1307
             where action is one of:
1308

  
1309
             ADD [ COLUMN ] column data_type [ COLLATE collation ] [ column_constraint [ ... ] ]
1310
             DROP [ COLUMN ] [ IF EXISTS ] column [ RESTRICT | CASCADE ]
1311
             ALTER [ COLUMN ] column [ SET DATA ] TYPE data_type [ COLLATE collation ] [ USING expression ]
1312
             ALTER [ COLUMN ] column SET DEFAULT expression
1313
             ALTER [ COLUMN ] column DROP DEFAULT
1314
             ALTER [ COLUMN ] column { SET | DROP } NOT NULL
1315
             ALTER [ COLUMN ] column SET STATISTICS integer
1316
             ALTER [ COLUMN ] column SET ( attribute_option = value [, ... ] )
1317
             ALTER [ COLUMN ] column RESET ( attribute_option [, ... ] )
1318
             ALTER [ COLUMN ] column SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN }
1319
             ADD table_constraint [ NOT VALID ]
1320
             ADD table_constraint_using_index
1321
             VALIDATE CONSTRAINT constraint_name
1322
             DROP CONSTRAINT [ IF EXISTS ]  constraint_name [ RESTRICT | CASCADE ]
1323
             DISABLE TRIGGER [ trigger_name | ALL | USER ]
1324
             ENABLE TRIGGER [ trigger_name | ALL | USER ]
1325
             ENABLE REPLICA TRIGGER trigger_name
1326
             ENABLE ALWAYS TRIGGER trigger_name
1327
             DISABLE RULE rewrite_rule_name
1328
             ENABLE RULE rewrite_rule_name
1329
             ENABLE REPLICA RULE rewrite_rule_name
1330
             ENABLE ALWAYS RULE rewrite_rule_name
1331
             CLUSTER ON index_name
1332
             SET WITHOUT CLUSTER
1333
             SET WITH OIDS
1334
             SET WITHOUT OIDS
1335
             SET ( storage_parameter = value [, ... ] )
1336
             RESET ( storage_parameter [, ... ] )
1337
             INHERIT parent_table
1338
             NO INHERIT parent_table
1339
             OF type_name
1340
             NOT OF
1341
             OWNER TO new_owner
1342
             SET TABLESPACE new_tablespace
1343

  
1344
             and table_constraint_using_index is:
1345

  
1346
             [ CONSTRAINT constraint_name ]
1347
             { UNIQUE | PRIMARY KEY } USING INDEX index_name
1348
             [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
1349

  
1350
             */
1351

  
1436
            if( this.isEmpty() ) {
1437
                return sqls;
1438
            }
1352 1439
            for (String column : drops) {
1353 1440
                StringBuilder builder = new StringBuilder();
1354 1441
                builder.append("ALTER TABLE ");
......
1367 1454
                if( column.getType() == DataTypes.INT && column.isAutomatic() ) {
1368 1455
                    builder.append(" SERIAL");
1369 1456
                } else {
1370
                    builder.append(sqltype(column.getType(), column.getPrecision(), column.getSize()));
1457
                    builder.append(
1458
                        sqltype(
1459
                            column.getType(), 
1460
                            column.getPrecision(), 
1461
                            column.getSize(),
1462
                            column.getGeometryType(),
1463
                            column.getGeometrySubtype()
1464
                        )
1465
                    );
1371 1466
                }
1372 1467
                if (column.getDefaultValue() == null) {
1373 1468
                    if (column.allowNulls()) {
......
1387 1482
                    builder.append(" PRIMARY KEY");
1388 1483
                }
1389 1484
                sqls.add(builder.toString());
1390
                if( column.isIndexed() ) {
1391
                    String sql;
1392
                    String name = "idx_" + this.table().getName() + "_" + column.getName();
1393
                    if( column.isGeometry() ) {
1394
                        sql = MessageFormat.format(
1395
                            config.getString(SQLConfig.CREATE_INDEX_name_ON_table_USING_GIST_column),
1396
                            name,
1397
                            this.table().toString(),
1398
                            column.getName()
1399
                        );
1400
                    } else {
1401
                        sql = MessageFormat.format(
1402
                            config.getString(SQLConfig.CREATE_INDEX_name_ON_table_column),
1403
                            name,
1404
                            this.table().toString(),
1405
                            column.getName()
1406
                        );
1407
                    }
1408
                    sqls.add(sql);
1409
                }
1410 1485
            }
1411 1486
            for (ColumnDescriptorBuilderBase column : alters) {
1412 1487
                StringBuilder builder = new StringBuilder();
......
1418 1493
                if( column.getType() == DataTypes.INT && column.isAutomatic() ) {
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff