Revision 26

View differences:

tags/org.gvsig.mysql-2.4.0/org.gvsig.mysql.provider/src/main/java/org/gvsig/mysql/dal/operations/MySQLFetchFeatureTypeOperation.java
1

  
2
package org.gvsig.mysql.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.operations.FetchFeatureTypeOperation;
22
import org.gvsig.fmap.geom.Geometry;
23
import org.gvsig.fmap.geom.GeometryLocator;
24
import org.gvsig.fmap.geom.GeometryManager;
25
import org.gvsig.fmap.geom.type.GeometryType;
26

  
27
public class MySQLFetchFeatureTypeOperation extends FetchFeatureTypeOperation {
28

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

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

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

  
67
    @Override
68
    protected int getDataTypeFromMetadata(
69
            ResultSetMetaData rsMetadata,
70
            int colIndex
71
        ) throws SQLException {
72
        // En SpatiaLite no existe el tipo de dato Geometria, las geometrias
73
        // se guardan en un BLOB, y en getColumnTypeName se indica el tipo
74
        // de la geometria.
75
        if( rsMetadata.getColumnType(colIndex) != java.sql.Types.BINARY ) {
76
            return super.getDataTypeFromMetadata(rsMetadata, colIndex);
77
        }
78
        String typeName = rsMetadata.getColumnTypeName(colIndex);
79
        GeometryType gt = getGeometryTypeFromSpatiaLiteTypeName(typeName);
80
        if( gt==null ) {
81
            return super.getDataTypeFromMetadata(rsMetadata, colIndex);
82
        }
83
        return DataTypes.GEOMETRY;
84
    }
85
        
86
    @Override
87
    protected void fetchGeometryTypeAndSRS(
88
            EditableFeatureAttributeDescriptor attr,
89
            ResultSetMetaData rsMetadata,
90
            int colIndex
91
        ) {
92
        if( attr.getType()!=DataTypes.GEOMETRY ) {
93
            return;
94
        }
95
        try {
96
            String typeName = rsMetadata.getColumnTypeName(colIndex);
97
            GeometryType gt = getGeometryTypeFromSpatiaLiteTypeName(typeName);
98
            if( gt != null ) {
99
                attr.setGeometryType(gt);
100

  
101
                JDBCSQLBuilderBase sqlbuilder = this.createSQLBuilder();
102
                sqlbuilder.select().column().name("f_table_name");
103
                sqlbuilder.select().column().name("f_geometry_column");
104
                // sqlbuilder.select().column().name("geometry_type");
105
                sqlbuilder.select().column().name("type");
106
                sqlbuilder.select().column().name("coord_dimension");
107
                sqlbuilder.select().column().name("srid");
108
                // sqlbuilder.select().column().name("spatial_index_enabled");
109
                sqlbuilder.select().where().set(
110
                        sqlbuilder.eq(
111
                                sqlbuilder.column("f_table_name"),
112
                                sqlbuilder.constant(this.getTablename())
113
                        )
114
                );                
115
                sqlbuilder.select().where().and(
116
                        sqlbuilder.eq(
117
                                sqlbuilder.column("f_geometry_column"),
118
                                sqlbuilder.constant(attr.getName())
119
                        )
120
                );         
121
                sqlbuilder.select().from().table().name("geometry_columns");
122
                Statement st = null;
123
                ResultSet rs = null;
124
                int srsid = -1;
125
                try {
126
                    st = this.getConnection().createStatement();
127
                    rs = JDBCUtils.executeQuery(st, sqlbuilder.toString());
128
                    if (rs.next()) {
129
                        srsid = rs.getInt("srid");
130
                    }
131
                } catch(Exception ex) {
132
                    logger.warn("Can't read SRS from DDBB.",ex);
133
                } finally {
134
                    JDBCUtils.closeQuietly(rs);
135
                    JDBCUtils.closeQuietly(st);
136
                }
137
                if( srsid > 0 ) {
138
                    attr.setSRS(this.helper.getProjectionFromSRSId(srsid));
139
                }
140
            }
141
        
142
        
143
        } catch (SQLException ex) {
144
            // Do nothing
145
        }
146
    }
147

  
148
    private GeometryType getGeometryTypeFromSpatiaLiteTypeName(String typeName) {
149
        if( spatialiteGeometryTypes==null ) {
150
            GeometryManager manager = GeometryLocator.getGeometryManager();
151
            spatialiteGeometryTypes = new HashMap<>();
152
            spatialiteGeometryTypes.put("POINT", getGT(manager, Geometry.TYPES.POINT,Geometry.SUBTYPES.GEOM2D));
153
            
154
            spatialiteGeometryTypes.put("LINESTRING", getGT(manager, Geometry.TYPES.LINE,Geometry.SUBTYPES.GEOM2D));
155
            
156
            spatialiteGeometryTypes.put("POLYGON", getGT(manager, Geometry.TYPES.POLYGON,Geometry.SUBTYPES.GEOM2D));
157

  
158
            spatialiteGeometryTypes.put("MULTIPOINT", getGT(manager, Geometry.TYPES.MULTIPOINT,Geometry.SUBTYPES.GEOM2D));
159

  
160
            spatialiteGeometryTypes.put("MULTILINESTRING", getGT(manager, Geometry.TYPES.MULTILINE,Geometry.SUBTYPES.GEOM2D));
161

  
162
            spatialiteGeometryTypes.put("MULTIPOLYGON", getGT(manager, Geometry.TYPES.MULTIPOLYGON,Geometry.SUBTYPES.GEOM2D));
163

  
164
            spatialiteGeometryTypes.put("GEOMETRY", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM2D));
165
        }
166
        return spatialiteGeometryTypes.get(typeName);
167
    }
168
    
169
}
tags/org.gvsig.mysql-2.4.0/org.gvsig.mysql.provider/src/main/java/org/gvsig/mysql/dal/operations/MySQLOperationsFactory.java
1

  
2
package org.gvsig.mysql.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.CalculateEnvelopeOfColumnOperation;
9
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.FetchFeatureTypeOperation;
10
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.OperationsFactoryBase;
11
import org.gvsig.fmap.geom.primitive.Envelope;
12

  
13

  
14
public class MySQLOperationsFactory extends OperationsFactoryBase {
15
    
16
    public MySQLOperationsFactory(JDBCHelper helper) {
17
        super(helper);
18
    }
19

  
20
    @Override
21
    public FetchFeatureTypeOperation createFetchFeatureType(EditableFeatureType type, String database, String schema, String table, List<String> primaryKeys, String defaultGeometryField, IProjection crs) {
22
        return new MySQLFetchFeatureTypeOperation(helper, type, database, schema, table, primaryKeys, defaultGeometryField, crs);
23
    }
24

  
25
    @Override
26
    public CalculateEnvelopeOfColumnOperation createCalculateEnvelopeOfColumn(String subquery, String database, String schema, String table, String columnName, String baseFilter, Envelope workingArea, IProjection crs) {
27
        return new MySQLCalculateEnvelopeOfColumnOperation(helper, subquery, table, schema, table, columnName, baseFilter, workingArea, crs);
28
    }
29
    
30
    
31
    
32
}
tags/org.gvsig.mysql-2.4.0/org.gvsig.mysql.provider/src/main/java/org/gvsig/mysql/dal/operations/MySQLCalculateEnvelopeOfColumnOperation.java
1
package org.gvsig.mysql.dal.operations;
2

  
3
import java.sql.Connection;
4
import java.sql.ResultSet;
5
import java.sql.Statement;
6
import org.apache.commons.lang3.StringUtils;
7
import org.cresques.cts.IProjection;
8
import org.gvsig.fmap.dal.exception.DataException;
9
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
10
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
11
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
12
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
13
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.CalculateEnvelopeOfColumnOperation;
14
import org.gvsig.fmap.geom.Geometry;
15
import org.gvsig.fmap.geom.GeometryLocator;
16
import org.gvsig.fmap.geom.primitive.Envelope;
17

  
18
public class MySQLCalculateEnvelopeOfColumnOperation extends CalculateEnvelopeOfColumnOperation {
19

  
20
    public MySQLCalculateEnvelopeOfColumnOperation(JDBCHelper helper, String subquery, String dbName, String schemaName, String tableName, String columnName, String baseFilter, Envelope limit, IProjection crs) {
21
        super(helper, subquery, dbName, schemaName, tableName, columnName, baseFilter, limit, crs);
22
    }
23

  
24
    @Override
25
    public Envelope calculateEnvelopeOfColumn(
26
            Connection conn,
27
            String subquery,
28
            String dbName,
29
            String schemaName,
30
            String tableName,
31
            String columnName,
32
            String baseFilter,
33
            Envelope limit,
34
            IProjection crs
35
    ) throws DataException {
36

  
37
        //
38
        // MySQL no soporta la funcion de agregado ST_Extent
39
        //
40
        JDBCSQLBuilderBase sqlbuilder = this.createSQLBuilder();
41
        sqlbuilder.select().column().value(
42
            sqlbuilder.getAsGeometry(
43
                sqlbuilder.ST_Envelope(
44
                        sqlbuilder.column(columnName)
45
                )
46
            )
47
        );
48

  
49
        if (StringUtils.isEmpty(subquery)) {
50
            sqlbuilder.select().from().table().database(dbName).schema(schemaName).name(tableName);
51
        } else {
52
            sqlbuilder.select().from().subquery(subquery);
53
        }
54

  
55
        if (StringUtils.isEmpty(baseFilter)) {
56
            if (limit != null) {
57
                sqlbuilder.select().where().set(
58
                        sqlbuilder.ST_Intersects(
59
                                sqlbuilder.ST_Envelope(
60
                                        sqlbuilder.column(columnName)
61
                                ),
62
                                sqlbuilder.ST_Envelope(
63
                                        sqlbuilder.geometry(limit.getGeometry(), crs)
64
                                )
65
                        )
66
                );
67
            }
68
        } else {
69
            sqlbuilder.select().where().set( sqlbuilder.custom(baseFilter) );
70
            if (limit != null) {
71
                sqlbuilder.select().where().and(
72
                        sqlbuilder.ST_Intersects(
73
                            sqlbuilder.ST_Envelope(
74
                                    sqlbuilder.column(columnName)
75
                            ),
76
                            sqlbuilder.ST_Envelope(
77
                                    sqlbuilder.geometry(limit.getGeometry(), crs)
78
                            )
79
                        )
80
                );
81
            }
82
        }
83

  
84
        String sql = sqlbuilder.select().toString();
85

  
86
        Statement st = null;
87
        ResultSet rs = null;
88
        try {
89
            st = conn.createStatement();
90
            rs = JDBCUtils.executeQuery(st, sql);
91
            Envelope env = GeometryLocator.getGeometryManager().createEnvelope(Geometry.SUBTYPES.GEOM2D);
92
            while( rs.next() ) { 
93
                Geometry geom = this.helper.getGeometryFromColumn(rs, 1);
94
                if (geom != null) {
95
                    env.add(geom);
96
                }
97
            }
98
            return env;
99
        } catch (Exception ex) {
100
            throw new JDBCSQLException(ex);
101
        } finally {
102
            JDBCUtils.closeQuietly(st);
103
            JDBCUtils.closeQuietly(rs);
104
        }
105
    }
106

  
107
}
tags/org.gvsig.mysql-2.4.0/org.gvsig.mysql.provider/src/main/java/org/gvsig/mysql/dal/MySQLHelper.java
1
/* gvSIG. Geographic Information System of the Valencian Government
2
 *
3
 * Copyright (C) 2007-2016 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 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
 */
22
package org.gvsig.mysql.dal;
23

  
24
import java.sql.Connection;
25
import java.sql.SQLException;
26
import java.text.MessageFormat;
27
import org.apache.commons.dbcp.BasicDataSource;
28
import org.cresques.cts.IProjection;
29
import org.gvsig.fmap.dal.SQLBuilder;
30
import org.gvsig.fmap.dal.resource.exception.AccessResourceException;
31
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters;
32
import org.gvsig.fmap.dal.store.jdbc.JDBCNewStoreParameters;
33
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
34
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
35
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCDriverClassNotFoundException;
36
import org.gvsig.fmap.dal.store.jdbc2.OperationsFactory;
37
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCHelperBase;
38
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
39
import org.gvsig.mysql.dal.operations.MySQLOperationsFactory;
40

  
41
import org.slf4j.Logger;
42
import org.slf4j.LoggerFactory;
43

  
44
public class MySQLHelper extends JDBCHelperBase {
45

  
46
    static final Logger logger = LoggerFactory.getLogger(MySQLHelper.class);
47

  
48
    public static final String NAME = "MySQL";
49
    public static final String MySQLJDBCDriver = "com.mysql.jdbc.Driver";
50
    
51
    public static String getConnectionURL(MySQLConnectionParameters params) {
52
        String connectionURL = MessageFormat.format(
53
                "jdbc:mysql://{0}:{1,number,#}/{2}",
54
                params.getHost(),
55
                params.getPort(),
56
                params.getDBName()
57
        );
58
        logger.debug("connectionURL: {}", connectionURL);
59
        return connectionURL;
60
    }
61

  
62
    private static class ConnectionProvider {
63

  
64
        private static boolean needRegisterDriver = true;
65

  
66
        private BasicDataSource dataSource = null;
67

  
68
        private final MySQLConnectionParameters connectionParameters;
69

  
70
        public ConnectionProvider(MySQLConnectionParameters connectionParameters) {
71
            this.connectionParameters = connectionParameters;
72
        }
73

  
74
        public Connection getConnection() throws SQLException {
75
            if (this.dataSource == null) {
76
                this.dataSource = this.createDataSource();               
77
            }
78
            Connection conn = this.dataSource.getConnection();
79
            return conn;
80
        }
81

  
82
        private BasicDataSource createDataSource() throws SQLException {
83
            if (!this.isRegistered()) {
84
                this.registerDriver();
85
            }
86
            JDBCConnectionParameters params = connectionParameters;
87

  
88
            BasicDataSource dataSource = new BasicDataSource();
89
            dataSource.setDriverClassName(params.getJDBCDriverClassName());
90
            
91
            dataSource.setUsername(params.getUser());
92
            dataSource.setPassword(params.getPassword());
93
            dataSource.setUrl(params.getUrl());
94

  
95
            dataSource.setMaxWait(60L * 1000);
96
            return dataSource;
97
        }
98

  
99
        private boolean isRegistered() {
100
            return needRegisterDriver;
101
        }
102

  
103
        public void registerDriver() throws SQLException {
104
            String className = this.connectionParameters.getJDBCDriverClassName();
105
            if (className == null) {
106
                return;
107
            }
108
            try {
109
                Class theClass = Class.forName(className);
110
                if (theClass == null) {
111
                    throw new JDBCDriverClassNotFoundException(MySQLLibrary.NAME, className);
112
                }
113
            } catch (Exception e) {
114
                throw new SQLException("Can't register JDBC driver '" + className + "'.", e);
115
            }
116
            needRegisterDriver = false;
117
        }
118

  
119
    }
120

  
121
    private ConnectionProvider connectionProvider = null;
122
   
123
    public MySQLHelper(JDBCConnectionParameters connectionParameters) {
124
        super(connectionParameters);
125
    }
126

  
127
    @Override
128
    public Connection getConnection() throws AccessResourceException {
129
        try {
130
            if (this.connectionProvider == null) {
131
                this.connectionProvider = new ConnectionProvider(this.getConnectionParameters());
132
            }
133
            return this.connectionProvider.getConnection();
134
        } catch (SQLException ex) {
135
            throw new AccessResourceException(MySQLLibrary.NAME, ex);
136
        }
137
    }
138
    
139
    @Override
140
    public MySQLConnectionParameters getConnectionParameters() {
141
        return (MySQLConnectionParameters) super.getConnectionParameters();
142
    }
143
    
144
    @Override
145
    public String getConnectionURL() {
146
        return getConnectionURL(this.getConnectionParameters());
147
    }
148

  
149
    @Override
150
    protected String getResourceType() {
151
        return MySQLLibrary.NAME;
152
    }
153

  
154
    @Override
155
    public String getProviderName() {
156
        return MySQLLibrary.NAME;
157
    }
158

  
159
    @Override
160
    public JDBCSQLBuilderBase createSQLBuilder() {
161
        return new MySQLSQLBuilder(this);
162
    }
163
    
164
    @Override
165
    public OperationsFactory getOperations() {
166
        if (this.operationsFactory == null) {
167
            this.operationsFactory = new MySQLOperationsFactory(this);
168
        }
169
        return operationsFactory;
170
    }
171

  
172
    @Override
173
    public SQLBuilder.GeometrySupportType getGeometrySupportType() {
174
        return SQLBuilder.GeometrySupportType.WKB;
175
    }
176

  
177
    @Override
178
    public boolean hasSpatialFunctions() {
179
        return true;
180
    }
181

  
182
    @Override
183
    public boolean canWriteGeometry(int geometryType, int geometrySubtype) {
184
        return true;
185
    }
186

  
187
    @Override
188
    public String getQuoteForIdentifiers() {
189
        return "\"";
190
    }
191

  
192
    @Override
193
    public boolean allowAutomaticValues() {
194
        return true;
195
    }
196

  
197
    @Override
198
    public boolean supportOffsetInSelect() {
199
        return true;
200
    }
201

  
202
    @Override
203
    public String getQuoteForStrings() {
204
        return "'";
205
    }
206

  
207
    @Override
208
    public int getSRSCode(IProjection crs) {
209
        // TODO: ir a buscarlo a la BBDD a ver donde puede estar
210
        return super.getSRSCode(crs);
211
    }
212
    
213
    @Override
214
    public IProjection getProjectionFromSRSId(int srsid) {
215
        // TODO: ir a buscarlo a la BBDD a ver donde puede estar
216
        return super.getProjectionFromSRSId(srsid);
217
    }
218

  
219
    @Override
220
    public String getSourceId(JDBCStoreParameters parameters) {
221
        return parameters.getDBName() + "." + 
222
               parameters.getSchema()+ "." + 
223
               parameters.getTable();
224
    }
225

  
226
    @Override
227
    public JDBCNewStoreParameters createNewStoreParameters() {
228
        return new MySQLNewStoreParameters();
229
    }
230

  
231
    @Override
232
    public JDBCStoreParameters createOpenStoreParameters() {
233
        return new MySQLStoreParameters();
234
    }
235

  
236
    @Override
237
    public JDBCServerExplorerParameters createServerExplorerParameters() {
238
        return new MySQLExplorerParameters();
239
    }
240

  
241
}
tags/org.gvsig.mysql-2.4.0/org.gvsig.mysql.provider/src/main/java/org/gvsig/mysql/dal/MySQLStoreProviderFactory.java
1

  
2
package org.gvsig.mysql.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 MySQLStoreProviderFactory extends JDBCStoreProviderFactory {
15

  
16
    private static final String NAME = MySQLLibrary.NAME;
17
    
18
    public MySQLStoreProviderFactory() {
19
        super(
20
                NAME, 
21
                "MySQL store"
22
        );
23
    }
24

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

  
38
    @Override
39
    public JDBCStoreParameters createParameters() {
40
        JDBCStoreParameters params = new MySQLStoreParameters();
41
        return params;
42
    }
43
    
44
}
tags/org.gvsig.mysql-2.4.0/org.gvsig.mysql.provider/src/main/java/org/gvsig/mysql/dal/MySQLStoreParameters.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.mysql.dal;
23

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

  
27
public class MySQLStoreParameters extends JDBCStoreParameters implements MySQLConnectionParameters {
28

  
29
    private final MySQLConnectionParametersHelper helper;
30
    
31
    public MySQLStoreParameters() {
32
        super(
33
                MySQLLibrary.NAME + "StoreParameters",
34
                MySQLLibrary.NAME
35
        );
36
        this.helper = new MySQLConnectionParametersHelper(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
}
tags/org.gvsig.mysql-2.4.0/org.gvsig.mysql.provider/src/main/java/org/gvsig/mysql/dal/MySQLConnectionParameters.java
1

  
2
package org.gvsig.mysql.dal;
3

  
4
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters;
5

  
6
public interface MySQLConnectionParameters extends JDBCConnectionParameters {
7
    
8
}
tags/org.gvsig.mysql-2.4.0/org.gvsig.mysql.provider/src/main/java/org/gvsig/mysql/dal/MySQLConnectionParametersHelper.java
1

  
2
package org.gvsig.mysql.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 MySQLConnectionParametersHelper {
11

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

  
19
    public String getUrl() {
20
        String url = (String) this.getDynValue(JDBCConnectionParameters.URL_PARAMTER_NAME);
21
        if( StringUtils.isEmpty(url) ) {
22
            url = MySQLHelper.getConnectionURL((MySQLConnectionParameters) this.parameters);
23
            this.setDynValue(JDBCConnectionParameters.URL_PARAMTER_NAME,url);
24
        }
25
        return url;
26
    }
27
    
28
    public void validate() throws ValidateDataParametersException {
29
        // Do nothing
30
    }
31

  
32
    private Object getDynValue(String name) {
33
        return ((DataParameters)this.parameters).getDynValue(name);
34
    }
35
    
36
    private void setDynValue(String name, Object value) {
37
        ((DataParameters)this.parameters).setDynValue(name,value);
38
    }
39
        
40
}
tags/org.gvsig.mysql-2.4.0/org.gvsig.mysql.provider/src/main/java/org/gvsig/mysql/dal/MySQLExplorerParameters.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.mysql.dal;
26

  
27
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
28
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
29

  
30
public class MySQLExplorerParameters extends
31
        JDBCServerExplorerParameters 
32
    implements
33
        MySQLConnectionParameters
34
    {
35
    
36
    private final MySQLConnectionParametersHelper helper;
37

  
38
    public MySQLExplorerParameters() {
39
        super(
40
                MySQLLibrary.NAME + "ServerExplorerParameters",
41
                MySQLLibrary.NAME
42
        );
43
        this.helper = new MySQLConnectionParametersHelper(this);
44
    }
45

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

  
57
}
tags/org.gvsig.mysql-2.4.0/org.gvsig.mysql.provider/src/main/java/org/gvsig/mysql/dal/MySQLLibrary.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.mysql.dal;
23

  
24
import org.gvsig.fmap.dal.DALLibrary;
25
import org.gvsig.fmap.dal.DALLocator;
26
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
27
import org.gvsig.fmap.dal.store.db.DBHelper;
28
import org.gvsig.fmap.dal.store.jdbc2.JDBCLibrary;
29
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCStoreProviderBase;
30
import org.gvsig.metadata.exceptions.MetadataException;
31
import org.gvsig.tools.library.AbstractLibrary;
32
import org.gvsig.tools.library.LibraryException;
33

  
34
public class MySQLLibrary extends AbstractLibrary {
35

  
36
    public static final String NAME = "MySQL";
37

  
38
    @Override
39
    public void doRegistration() {
40
        registerAsServiceOf(DALLibrary.class);
41
        require(JDBCLibrary.class);
42
    }
43

  
44
    @Override
45
    protected void doInitialize() throws LibraryException {
46
    }
47

  
48
    @Override
49
    protected void doPostInitialize() throws LibraryException {
50
        LibraryException ex = null;
51

  
52
        DataManagerProviderServices dataman = 
53
                (DataManagerProviderServices) DALLocator.getDataManager();
54

  
55
        try {
56
            Class.forName(MySQLHelper.MySQLJDBCDriver);
57
        } catch(Throwable th) {
58
            MySQLHelper.logger.warn("Can't load MySQL JDBC Driver.",th);
59
        }
60
        
61
        DBHelper.registerParametersDefinition(
62
                NAME + "StoreParameters",
63
                MySQLStoreParameters.class,
64
                dataman.getResourceAsStream(this, NAME + "Parameters.xml")
65
        );
66
        DBHelper.registerParametersDefinition(
67
                NAME + "NewStoreParameters",
68
                MySQLNewStoreParameters.class,
69
                dataman.getResourceAsStream(this, NAME + "Parameters.xml")
70
        );
71
        DBHelper.registerParametersDefinition(
72
                NAME + "ServerExplorerParameters",
73
                MySQLExplorerParameters.class,
74
                dataman.getResourceAsStream(this, NAME + "Parameters.xml")
75
        );
76
//        DBHelper.registerParametersDefinition(
77
//                NAME + "ResourceParameters",
78
//                MySQLResourceParameters.class,
79
//                dataman.getResourceAsStream(this, NAME + "Parameters.xml")
80
//        );
81
        try {
82
            DBHelper.registerMetadataDefinition(
83
                NAME,
84
                JDBCStoreProviderBase.class,
85
                dataman.getResourceAsStream(this, NAME + "Metadata.xml")
86
            );
87
        } catch (MetadataException e) {
88
            ex = new LibraryException(this.getClass(), e);
89
        }
90

  
91
//        ResourceManagerProviderServices resman = (ResourceManagerProviderServices) DALLocator
92
//                .getResourceManager();
93
//
94
//        if (!resman.getResourceProviders().contains(NAME)) {
95
//            resman.register(NAME,
96
//                "Resource for " + NAME,
97
//                MySQLResource.class,
98
//                MySQLResourceParameters.class
99
//            );
100
//        }
101

  
102
        if (!dataman.getStoreProviderRegister().exits(NAME)) {
103
            dataman.registerStoreProviderFactory(new MySQLStoreProviderFactory());
104
        }
105

  
106
        if (!dataman.getServerExplorerRegister().exits(NAME)) {
107
            dataman.registerServerExplorerFactory(new MySQLExplorerFactory());
108
        }
109
        if (ex != null) {
110
            throw ex;
111
        }
112
    }
113

  
114
}
tags/org.gvsig.mysql-2.4.0/org.gvsig.mysql.provider/src/main/java/org/gvsig/mysql/dal/MySQLSQLBuilder.java
1
package org.gvsig.mysql.dal;
2

  
3
import java.util.ArrayList;
4
import java.util.List;
5
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
6

  
7
public class MySQLSQLBuilder extends JDBCSQLBuilderBase {
8

  
9
    private final MySQLHelper helper;
10

  
11
    public MySQLSQLBuilder(MySQLHelper helper) {
12
        super();
13
        
14
        this.helper = helper;
15
        
16
        //
17
        // MySQL 5.5, SQL functions reference list
18
        //
19
        // https://dev.mysql.com/doc/refman/5.5/en/sql-syntax.html
20
        // https://dev.mysql.com/doc/refman/5.5/en/using-spatial-data.html
21
        //
22
        // https://dev.mysql.com/doc/refman/5.7/en/spatial-function-reference.html
23
        //
24
        
25
        config.set(SQLConfig.default_schema, "");
26
        config.set(SQLConfig.quote_for_identifiers, "`");
27
        config.set(SQLConfig.allowAutomaticValues, true);
28
        config.set(SQLConfig.geometry_type_support, this.helper.getGeometrySupportType());
29
        config.set(SQLConfig.has_spatial_functions, this.helper.hasSpatialFunctions());
30

  
31
        config.remove_functionality(SQLConfig.DELETE_GEOMETRY_COLUMN_FROM_TABLE_schema_table);
32
        config.remove_functionality(SQLConfig.DELETE_GEOMETRY_COLUMN_FROM_TABLE_table);
33
         
34
        
35
        // MySQL no tiene funciones de agregado sobre geometrias.
36
        // Esto no es nada eficiente y fallara con tablas grandes.
37
        // https://forums.mysql.com/read.php?23,249284,249284#msg-249284
38
        config.set(SQLConfig.ST_ExtentAggregate, "ST_AsWKB(ST_Envelope(ST_GeomCollFromText(GROUP_CONCAT(ST_AsWKT({0})))))");
39
        config.set(SQLConfig.ST_UnionAggregate, "null");
40
        
41
        
42
                
43
        config.set(SQLConfig.UPDATE_TABLE_STATISTICS_table,"ANALYZE TABLE {0}");
44
        
45
        config.set(SQLConfig.lcase, "lower({0})");
46
        config.set(SQLConfig.ucase, "upper({0})");
47
        config.set(SQLConfig.operator_ILIKE, "lower({0}) LIKE lower({1})");
48
        config.set(SQLConfig.isNull, "( ({0}) IS NULL )");
49
        config.set(SQLConfig.notIsNull, "( ({0}) IS NOT NULL )");
50

  
51
        config.set(SQLConfig.type_boolean, "BIT");
52
        config.set(SQLConfig.type_byte, "TINYINT");
53
        config.set(SQLConfig.type_bytearray, "BINARY");
54
        config.set(SQLConfig.type_geometry, "GEOMETRY");
55
        config.set(SQLConfig.type_char, "TEXT");
56
        config.set(SQLConfig.type_date, "DATETIME");
57
        config.set(SQLConfig.type_double, "DOUBLE"); 
58
        config.set(SQLConfig.type_numeric_p, "DECIMAL({0})");
59
        config.set(SQLConfig.type_numeric_ps, "DECIMAL({0},{1})");
60
        config.set(SQLConfig.type_bigdecimal, "DECIMAL");
61
        config.set(SQLConfig.type_float, "FLOAT");
62
        config.set(SQLConfig.type_int, "INTEGER");
63
        config.set(SQLConfig.type_long, "BIGINT");
64
        config.set(SQLConfig.type_string, "CHAR");
65
        config.set(SQLConfig.type_string_p, "VARCHAR({0})");
66
        config.set(SQLConfig.type_time, "TIME");
67
        config.set(SQLConfig.type_timestamp, "TIMESTAMP");
68
        config.set(SQLConfig.type_version, "VARCHAR(45)");
69
        config.set(SQLConfig.type_URI, "TEXT");
70
        config.set(SQLConfig.type_URL, "TEXT");
71
        config.set(SQLConfig.type_FILE, "TEXT");
72
        config.set(SQLConfig.type_FOLDER, "TEXT");        
73
    }
74

  
75
    public class MySQLTableNameBuilderBase extends TableNameBuilderBase {
76

  
77
        @Override
78
        public boolean has_schema() {
79
            return false;
80
        }
81
        
82
    }
83
    
84
    protected class MySQLCreateTableBuilder extends CreateTableBuilderBase {
85

  
86
        @Override
87
        public List<String> toStrings() {
88

  
89
            List<String> sqls = new ArrayList<>();
90
            StringBuilder builder = new StringBuilder();
91

  
92
            builder.append("CREATE TABLE ");
93
            builder.append(this.table.toString());
94
            builder.append(" (");
95
            boolean first = true;
96
            for (ColumnDescriptorBuilder column : columns) {
97
                if (first) {
98
                    first = false;
99
                } else {
100
                    builder.append(", ");
101
                }
102
                builder.append(identifier(column.getName()));
103
                builder.append(" ");
104
                builder.append(sqltype(column.getType(), column.getPrecision(), column.getSize()));
105
                if (column.isPrimaryKey()) {
106
                    builder.append(" PRIMARY KEY");
107
                }
108
                if( column.isAutomatic() ) {
109
                    builder.append(" AUTO_INCREMENT");
110
                }
111
                if (column.getDefaultValue() == null) {
112
                    if (column.allowNulls()) {
113
                        builder.append(" DEFAULT NULL");
114
                    }
115
                } else {
116
                    builder.append(" DEFAULT '");
117
                    builder.append(column.getDefaultValue().toString());
118
                    builder.append("'");
119
                }
120
                if (column.allowNulls()) {
121
                    builder.append(" NULL");
122
                } else {
123
                    builder.append(" NOT NULL");
124
                }
125
            }
126
            builder.append(" )");
127
            sqls.add(builder.toString());
128

  
129
            return sqls;
130
        }
131
    }
132

  
133
    public class MySQLSelectBuilderBase extends SelectBuilderBase {
134
        
135
        @Override
136
        protected boolean isValid(StringBuilder message) {
137
            if( message == null ) {
138
                message = new StringBuilder();
139
            }
140
            if( this.has_offset() && !this.has_order_by() ) {
141
                // Algunos gestores de BBDD requieren que se especifique un
142
                // orden para poder usar OFFSET. Como eso parece buena idea para
143
                // asegurar que siempre tengamos los mismo resultados, lo exijimos
144
                // siempre.
145
                message.append("Can't use OFFSET without an ORDER BY.");
146
                return false;
147
            }
148
            return true;
149
        }        
150
        
151
        @Override
152
        public String toString() {
153
            // MySQL requiere que si se especifica OFFSET deba especificarse
154
            // LIMIT obligatoriamente. Se le puede poner un LIMIT -1 cuando 
155
            // queramos un OFFSET sin especificar un LIMIT.
156
            StringBuilder builder = new StringBuilder();
157
            if( !isValid(builder) ) {
158
                throw new IllegalStateException(builder.toString());
159
            }
160
            builder.append("SELECT ");
161
            if( this.distinct ) {
162
                builder.append("DISTINCT ");
163
            }
164
            boolean first = true;
165
            for (SelectColumnBuilder column : columns) {
166
                if (first) {
167
                    first = false;
168
                } else {
169
                    builder.append(", ");
170
                }
171
                builder.append(column.toString());
172
            }
173

  
174
            if ( this.has_from() ) {
175
                builder.append(" FROM ");
176
                builder.append(this.from.toString());
177
            }
178
            if ( this.has_where() ) {
179
                builder.append(" WHERE ");
180
                builder.append(this.where.toString());
181
            }
182
            
183
            if( this.has_order_by() ) {
184
                builder.append(" ORDER BY ");
185
                first = true;
186
                for (OrderByBuilder item : this.order_by) {
187
                    if (first) {
188
                        first = false;
189
                    } else {
190
                        builder.append(", ");
191
                    }
192
                    builder.append(item.toString());                    
193
                }   
194
            }
195
            
196
            if ( this.has_limit() && this.has_offset() ) {
197
                builder.append(" LIMIT ");
198
                builder.append(this.limit);
199
                builder.append(" OFFSET ");
200
                builder.append(this.offset);
201
                
202
            } else if ( this.has_limit()) {
203
                builder.append(" LIMIT ");
204
                builder.append(this.limit);
205

  
206
            } else if ( this.has_offset() ) {
207
                // See https://dev.mysql.com/doc/refman/5.7/en/select.html#idm140126933499488
208
                builder.append(" LIMIT 18446744073709551615 OFFSET ");
209
                builder.append(this.offset);    
210
            }
211
            return builder.toString();
212

  
213
        }
214
    }
215

  
216
    @Override
217
    public String bytearray(byte[] data) {
218
        // MySQL usa un formato diferencte para especificar un array de 
219
        // bytes. En lugar de 0x... usa x'...' .
220
        StringBuilder builder = new StringBuilder();
221
        builder.append("x'");
222
        for (byte abyte : data) {
223
            int v = abyte & 0xff;
224
            builder.append(String.format("%02x", v));
225
        }
226
        builder.append("'");
227
        return builder.toString();
228
    }
229
    
230
    @Override
231
    protected TableNameBuilder createTableNameBuilder() {
232
        return new MySQLTableNameBuilderBase();
233
    }
234
    
235
    @Override
236
    protected CreateTableBuilder createCreateTableBuilder() {
237
        return new MySQLCreateTableBuilder();
238
    }
239

  
240
    @Override
241
    protected SelectBuilder createSelectBuilder() {
242
        return new MySQLSelectBuilderBase();
243
    }
244

  
245
}
tags/org.gvsig.mysql-2.4.0/org.gvsig.mysql.provider/src/main/java/org/gvsig/mysql/dal/MySQLExplorerFactory.java
1

  
2
package org.gvsig.mysql.dal;
3

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

  
13

  
14
public class MySQLExplorerFactory extends JDBCServerExplorerFactory {
15

  
16
    private static final String NAME = MySQLLibrary.NAME;
17
    
18
    public MySQLExplorerFactory() {
19
        super(
20
                NAME,
21
                "MySQL Server"
22
        );
23
    }
24

  
25
    @Override
26
    public JDBCServerExplorer create(
27
            DataServerExplorerParameters parameters, 
28
            DataServerExplorerProviderServices providerServices
29
        ) throws InitializeException {
30
        JDBCHelper helper = new MySQLHelper((JDBCConnectionParameters) parameters);
31
        JDBCServerExplorer server = helper.createServerExplorer(
32
                (JDBCServerExplorerParameters) parameters, 
33
                providerServices
34
        );
35
        return server;
36
    }
37
        
38

  
39
    @Override
40
    public JDBCServerExplorerParameters createParameters() {
41
        JDBCServerExplorerParameters params = new MySQLExplorerParameters();
42
        return params;    
43
    }
44
    
45
}
tags/org.gvsig.mysql-2.4.0/org.gvsig.mysql.provider/src/main/java/org/gvsig/mysql/dal/MySQLNewStoreParameters.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.mysql.dal;
23

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

  
27
public class MySQLNewStoreParameters 
28
    extends 
29
        JDBCNewStoreParameters 
30
    implements 
31
        MySQLConnectionParameters 
32
    {
33

  
34
    private final MySQLConnectionParametersHelper helper;
35
    
36
    public MySQLNewStoreParameters() {
37
        super(
38
            MySQLLibrary.NAME + "NewStoreParameters", 
39
            MySQLLibrary.NAME
40
        );
41
        this.helper = new MySQLConnectionParametersHelper(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
}
tags/org.gvsig.mysql-2.4.0/org.gvsig.mysql.provider/src/main/resources/META-INF/services/org.gvsig.tools.library.Library
1
org.gvsig.mysql.dal.MySQLLibrary
tags/org.gvsig.mysql-2.4.0/org.gvsig.mysql.provider/src/main/resources/org/gvsig/mysql/dal/MySQLMetadata.xml
1
<?xml version="1.0"?>
2
<definitions>
3
  <version>1.0.0</version>
4
  <classes>
5
    <class name="MySQL" namespace="Metadata">
6
      <extends>
7
      	<class name="JDBC2" namespace="Metadata"/>
8
      </extends>
9
      <description>Metadata for MySQL</description>
10
      <fields>
11
      </fields>
12
    </class>
13

  
14
  </classes>
15
</definitions>  
tags/org.gvsig.mysql-2.4.0/org.gvsig.mysql.provider/src/main/resources/org/gvsig/mysql/dal/MySQLParameters.xml
1
<?xml version="1.0"?>
2
<definitions>
3
  <version>1.0.0</version>
4
  <classes>
5
    <class name="MySQLResourceParameters">
6
      <extends>
7
        <class>JDBC2ResourceParameters</class>
8
      </extends>
9
      <fields>
10
        <field name="JDBCDriverClass" type="string" mandatory="true"
11
          defaultValue="com.mysql.jdbc.Driver" group="Advanced">
12
          <description>JDBC driver class for MySQL</description>
13
        </field>
14
        <field name="port" type="integer" mandatory="true"
15
          defaultValue="3306" group="Connection" hidden="false">
16
          <description></description>
17
        </field>
18
        <field name="host" type="string" mandatory="true" 
19
            defaultValue="localhost" group="Connection" hidden="false">
20
          <description></description>
21
        </field>
22
        <field name="dbname" type="string" mandatory="true" hidden="false" defaultValue="" group="Basic">
23
          <description></description>
24
        </field>
25
        <field name="schema" type="string" mandatory="false" hidden="true" defaultValue="" group="Basic">
26
          <description></description>
27
        </field>
28
        <field name="catalog" type="string" mandatory="false" hidden="true" defaultValue="" group="Basic">
29
          <description></description>
30
        </field>
31
        <field name="url" type="string" mandatory="false" hidden="false" defaultValue="" group="Basic">
32
          <description></description>
33
        </field>
34
        <field name="dbuser" type="string" mandatory="false" defaultValue="" group="Basic">
35
          <description></description>
36
        </field>
37
        <field name="password" type="string" mandatory="false" defaultValue="" group="Basic">
38
          <description></description>
39
        </field>           
40
      </fields>
41
    </class>
42

  
43
    <class name="MySQLStoreParameters">
44
      <extends>
45
        <class>JDBC2StoreParameters</class>
46
        <class>MySQLResourceParameters</class>
47
      </extends>
48
      <fields/>
49
    </class>
50

  
51
    <class name="MySQLNewStoreParameters">
52
      <extends>
53
        <class>JDBC2NewStoreParameters</class>
54
        <class>MySQLResourceParameters</class>
55
      </extends>
56
      <fields/>
57
    </class>
58

  
59

  
60
    <class name="MySQLServerExplorerParameters">
61
      <extends>
62
        <class>MySQLResourceParameters</class>
63
        <class>JDBC2ServerExplorerParameters</class>
64
      </extends>
65
      <fields/>
66
    </class>
67

  
68

  
69
  </classes>
70
</definitions>  
tags/org.gvsig.mysql-2.4.0/org.gvsig.mysql.provider/src/test/java/org/gvsig/mysql/dal/MySQLSQLBuilderTest.java
1
package org.gvsig.mysql.dal;
2

  
3
import java.util.ArrayList;
4
import java.util.List;
5
import org.apache.commons.lang3.ArrayUtils;
6
import org.cresques.cts.IProjection;
7
import org.gvsig.fmap.crs.CRSFactory;
8
import org.gvsig.fmap.dal.DALLocator;
9
import org.gvsig.fmap.dal.ExpressionBuilder;
10
import org.gvsig.fmap.dal.ExpressionBuilder.Parameter;
11
import org.gvsig.fmap.dal.ExpressionBuilder.Variable;
12
import org.gvsig.fmap.dal.SQLBuilder;
13
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
14
import org.gvsig.fmap.dal.store.db.DBHelper;
15
import org.gvsig.fmap.geom.DataTypes;
16
import org.gvsig.fmap.geom.Geometry;
17
import org.gvsig.fmap.geom.GeometryLocator;
18
import org.gvsig.fmap.geom.GeometryManager;
19
import org.gvsig.fmap.geom.primitive.Polygon;
20
import org.gvsig.tools.junit.AbstractLibraryAutoInitTestCase;
21

  
22
public class MySQLSQLBuilderTest extends AbstractLibraryAutoInitTestCase {
23

  
24
    private MySQLHelper helper;
25
    
26
    @Override
27
    protected void doSetUp() throws Exception {
28
        DataManagerProviderServices dataman = 
29
                (DataManagerProviderServices) DALLocator.getDataManager();
30

  
31
        DBHelper.registerParametersDefinition(
32
                MySQLLibrary.NAME + "StoreParameters",
33
                MySQLStoreParameters.class,
34
                dataman.getResourceAsStream(this, MySQLLibrary.NAME + "Parameters.xml")
35
        );
36
        
37
        MySQLStoreParameters params = new MySQLStoreParameters();
38
        params.setDBName("test.sqlite");
39
        params.setTable("test1");
40
        helper = new MySQLHelper(params);
41
    }
42
    
43
    List<String> getVariableNames(ExpressionBuilder builder) {
44
        List<String> vars = new ArrayList<>();
45
        for (Variable var : builder.getVariables()) {
46
            vars.add(var.getName());
47
        }
48
        return vars;
49
    }
50
    
51
    List<String> getParameterNames(ExpressionBuilder builder) {
52
        List<String> params = new ArrayList<>();
53
        for (Parameter param : builder.getParameters()) {
54
            String s;
55
            switch(param.getType()) {
56
                case Constant:
57
                    Object value = param.getValue();
58
                    if( value==null ) {
59
                        s = "null";
60
                    } else if( value instanceof String ) {
61
                        s = "'" + (String)value + "'";
62
                    } else {
63
                        s = value.toString();
64
                    }    
65
                    break;
66
                case Geometry:
67
                case Variable:
68
                default:
69
                    s = "\"" + param.getName() + "\"";
70
            }
71
            params.add(s);
72
        }
73
        return params;
74
    }
75
    
76
    public SQLBuilder createSQLBuilder() {
77
        return new MySQLSQLBuilder(helper);
78
    }
79
 
80
    public void testCalulateEnvelope() throws Exception {
81
        GeometryManager geometryManager = GeometryLocator.getGeometryManager();
82
        IProjection proj = CRSFactory.getCRS("EPSG:4326");
83
        
84
        Polygon limit = geometryManager.createPolygon(Geometry.SUBTYPES.GEOM2D);
85
        limit.addVertex(0, 0);
86
        limit.addVertex(0, 100);
87
        limit.addVertex(100, 100);
88
        limit.addVertex(100, 0);
89
        limit.addVertex(0, 0);
90
        
91
        SQLBuilder builder = createSQLBuilder();
92
        
93
        builder.select().column().value(
94
            builder.getAsGeometry(
95
              builder.ST_ExtentAggregate(
96
                builder.column("the_geom")
97
              )
98
            )
99
        ).as("envelope");
100
        builder.select().from().table().database("master").schema("dbo").name("test1");
101
        builder.select().where().set(
102
            builder.ST_Intersects(
103
                builder.ST_Envelope(
104
                    builder.column("the_geom")
105
                ),
106
                builder.geometry(limit, proj)
107
            )
108
        );
109
        builder.select().where().and(
110
                builder.custom("x = 27").add( builder.variable("x") )
111
        );
112
        
113
        System.out.println("# Test:: testCalulateEnvelope");
114
        System.out.println("# SQL:: " + builder.toString());
115
        System.out.println("# Variables:: " + ArrayUtils.toString(getVariableNames(builder)));
116
        System.out.println("# Parametros:: " + ArrayUtils.toString(getParameterNames(builder)));
117
    
118
        //# Test:: testCalulateEnvelope
119
        //# SQL:: SELECT ST_AsBinary(Extent("the_geom")) AS "envelope" FROM "test1" WHERE ST_Intersects((ST_Envelope("the_geom")), (ST_GeomFromWKB((x'000000000300000001000000050000000000000000000000000000000000000000000000004059000000000000405900000000000040590000000000004059000000000000000000000000000000000000000000000000000000000000'), (4326)))) AND x = 27
120
        //# Variables:: [the_geom, x]
121
        //# Parametros:: []  
122
        assertEquals(
123
                "SELECT ST_AsBinary(Extent(\"the_geom\")) AS \"envelope\" FROM \"test1\" WHERE ST_Intersects((ST_Envelope(\"the_geom\")), (ST_GeomFromWKB((x'000000000300000001000000050000000000000000000000000000000000000000000000004059000000000000405900000000000040590000000000004059000000000000000000000000000000000000000000000000000000000000'), (4326)))) AND x = 27",
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff