diff --git a/h2gis-functions/src/main/java/org/h2gis/functions/io/dbf/DBFDriverFunction.java b/h2gis-functions/src/main/java/org/h2gis/functions/io/dbf/DBFDriverFunction.java index d21977fca4..ce67b67fd6 100644 --- a/h2gis-functions/src/main/java/org/h2gis/functions/io/dbf/DBFDriverFunction.java +++ b/h2gis-functions/src/main/java/org/h2gis/functions/io/dbf/DBFDriverFunction.java @@ -211,7 +211,7 @@ public void importFile(Connection connection, String tableReference, File fileNa @Override public void importFile(Connection connection, String tableReference, File fileName, boolean deleteTables,ProgressVisitor progress) throws SQLException, IOException { - importFile(connection, tableReference, fileName,null, false, progress); + importFile(connection, tableReference, fileName,null, deleteTables, progress); } @Override diff --git a/h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GeoJsonReaderDriver.java b/h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GeoJsonReaderDriver.java index 2171057cd8..d45e439e48 100644 --- a/h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GeoJsonReaderDriver.java +++ b/h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GeoJsonReaderDriver.java @@ -23,15 +23,19 @@ import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; +import org.h2.value.ValueGeometry; +import org.h2.value.ValueNull; import org.h2gis.api.EmptyProgressVisitor; import org.h2gis.api.ProgressVisitor; import org.h2gis.utilities.JDBCUtilities; import org.h2gis.utilities.TableLocation; import org.locationtech.jts.geom.*; +import org.locationtech.jts.io.WKBWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; +import java.math.BigDecimal; import java.sql.*; import java.util.*; import java.util.zip.GZIPInputStream; @@ -51,7 +55,6 @@ */ public class GeoJsonReaderDriver { - private final static ArrayList geomTypes; private final File fileName; private final Connection connection; private static GeometryFactory GF; @@ -73,18 +76,9 @@ public class GeoJsonReaderDriver { private LinkedHashMap cachedColumnIndex; private static final int BATCH_MAX_SIZE = 100; - static { - geomTypes = new ArrayList(); - geomTypes.add(GeoJsonField.POINT); - geomTypes.add(GeoJsonField.MULTIPOINT); - geomTypes.add(GeoJsonField.LINESTRING); - geomTypes.add(GeoJsonField.MULTILINESTRING); - geomTypes.add(GeoJsonField.POLYGON); - geomTypes.add(GeoJsonField.MULTIPOLYGON); - - } private Set finalGeometryTypes; private JsonEncoding jsonEncoding; + private boolean hasZ =false; /** * Driver to import a GeoJSON file into a spatial table. @@ -132,7 +126,7 @@ public void read(ProgressVisitor progress, String tableReference) throws SQLExce this.tableLocation = TableLocation.parse(tableReference, isH2); if (deleteTable) { Statement stmt = connection.createStatement(); - stmt.execute("DROP TABLE IF EXISTS " + tableLocation); + stmt.execute("DROP TABLE IF EXISTS " + tableLocation.toString(isH2)); stmt.close(); } @@ -145,13 +139,12 @@ public void read(ProgressVisitor progress, String tableReference) throws SQLExce GF = new GeometryFactory(new PrecisionModel(), parsedSRID); fis = new FileInputStream(fileName); parseData(new GZIPInputStream(fis)); - setGeometryTypeConstraints(); connection.setAutoCommit(true); } else { throw new SQLException("Cannot create the table " + tableLocation + " to import the GeoJSON data"); } } else { - JDBCUtilities.createEmptyTable(connection, tableLocation.toString()); + JDBCUtilities.createEmptyTable(connection, tableLocation.toString(isH2)); } } else { throw new SQLException("The geojson read driver supports only geojson or gz extensions"); @@ -185,12 +178,11 @@ public void read(ProgressVisitor progress, String tableReference) throws SQLExce */ private void parseGeoJson(ProgressVisitor progress) throws SQLException, IOException { this.progress = progress.subProcess(100); - init();; + init(); if (parseMetadata(new FileInputStream(fileName))) { connection.setAutoCommit(false); GF = new GeometryFactory(new PrecisionModel(), parsedSRID); parseData(new FileInputStream(fileName)); - setGeometryTypeConstraints(); connection.setAutoCommit(true); } else { @@ -237,15 +229,20 @@ private boolean parseMetadata(InputStream is) throws SQLException, IOException { if (hasGeometryField) { StringBuilder createTable = new StringBuilder(); createTable.append("CREATE TABLE "); - createTable.append(tableLocation); + createTable.append(tableLocation.toString(isH2)); createTable.append(" ("); - //Add the geometry column - createTable.append("THE_GEOM GEOMETRY(geometry,").append(parsedSRID).append(")"); - + String finalGeometryType = GeoJsonField.GEOMETRY; + if (finalGeometryTypes.size() == 1) { + finalGeometryType = (String) finalGeometryTypes.iterator().next(); + createTable.append("THE_GEOM GEOMETRY(").append(hasZ?finalGeometryType+"Z":finalGeometryType).append(",").append(parsedSRID).append(")"); + } + else{ + createTable.append("THE_GEOM GEOMETRY(GEOMETRY,").append(parsedSRID).append(")"); + } cachedColumnIndex = new LinkedHashMap<>(); StringBuilder insertTable = new StringBuilder("INSERT INTO "); - insertTable.append(tableLocation).append(" VALUES(?"); + insertTable.append(tableLocation.toString(isH2)).append(" VALUES(ST_GeomFromWKB(?, ").append(parsedSRID).append(")"); int i = 1; for (Map.Entry columns : cachedColumnNames.entrySet()) { String columnName = columns.getKey(); @@ -655,6 +652,7 @@ private void parseCoordinateMetadata(JsonParser jp) throws IOException { jp.nextToken(); if (jp.getCurrentToken() != JsonToken.END_ARRAY) { jp.nextToken(); // exit array + hasZ=true; } jp.nextToken(); } @@ -842,7 +840,8 @@ private void setGeometry(JsonParser jp, Object[] values) throws IOException, SQL jp.nextToken(); // FIELD_NAME type jp.nextToken(); //VALUE_STRING Point String geometryType = jp.getText(); - values[0] = parseGeometry(jp, geometryType); + Geometry geom = parseGeometry(jp, geometryType); + values[0] = ValueGeometry.getFromGeometry(geom).getBytesNoCopy(); } } @@ -900,7 +899,8 @@ private void parseProperties(JsonParser jp, Object[] values) throws IOException, } else if (value == JsonToken.VALUE_NUMBER_FLOAT) { values[cachedColumnIndex.get(fieldName)] = jp.getValueAsDouble(); } else if (value == JsonToken.VALUE_NUMBER_INT) { - values[cachedColumnIndex.get(fieldName)] = jp.getBigIntegerValue(); + BigDecimal bigDecId = new BigDecimal(jp.getBigIntegerValue()); + values[cachedColumnIndex.get(fieldName)] = bigDecId; } else if (value == JsonToken.START_ARRAY) { ArrayList arrayList = parseArray(jp); values[cachedColumnIndex.get(fieldName)] = arrayList.toArray(); @@ -954,7 +954,6 @@ private void parseFeatures(JsonParser jp) throws IOException, SQLException { for (int i = 0; i < values.length; i++) { preparedStatement.setObject(i + 1, values[i]); } - preparedStatement.addBatch(); batchSize++; if (batchSize >= BATCH_MAX_SIZE) { @@ -968,16 +967,20 @@ private void parseFeatures(JsonParser jp) throws IOException, SQLException { featureCounter++; progress.setStep((int) ((featureCounter / nbFeature) * 100)); if (batchSize > 0) { - preparedStatement.executeBatch(); - connection.commit(); - preparedStatement.clearBatch(); + try { + preparedStatement.executeBatch(); + connection.commit(); + preparedStatement.clearBatch(); + }catch (SQLException ex){ + throw new SQLException(ex.getNextException()); + } } } else { throw new SQLException("Malformed GeoJSON file. Expected 'Feature', found '" + geomType + "'"); } } //LOOP END_ARRAY ] - log.info(featureCounter + " geojson features have been imported."); + log.info(featureCounter-1 + " geojson features have been imported."); } else { throw new SQLException("Malformed GeoJSON file. Expected 'features', found '" + firstParam + "'"); } @@ -1262,7 +1265,11 @@ private Coordinate parseCoordinate(JsonParser jp) throws IOException { //We look for a z value jp.nextToken(); if (jp.getCurrentToken() == JsonToken.END_ARRAY) { - coord = new Coordinate(x, y); + if(hasZ) { + coord = new Coordinate(x, y, 0); + }else { + coord = new Coordinate(x, y); + } } else { double z = jp.getDoubleValue(); jp.nextToken(); // exit array @@ -1373,21 +1380,6 @@ private String skipCRS(JsonParser jp) throws IOException { return jp.getText(); } - /** - * Adds the geometry type constraint and the SRID - */ - private void setGeometryTypeConstraints() throws SQLException { - String finalGeometryType = GeoJsonField.GEOMETRY; - if (finalGeometryTypes.size() == 1) { - finalGeometryType = (String) finalGeometryTypes.iterator().next(); - } - if (isH2) { - finalGeometryType = GeoJsonField.GEOMETRY;//workaround for H2 - connection.createStatement().execute(String.format("ALTER TABLE %s ALTER COLUMN the_geom %s", tableLocation.toString(), finalGeometryType)); - } else { - connection.createStatement().execute(String.format("ALTER TABLE %s ALTER COLUMN the_geom SET DATA TYPE geometry(%s,%d)", tableLocation.toString(), finalGeometryType, parsedSRID)); - } - } /** * Parses Json Array. Syntax: Json Array: {"member1": value1}, value2, diff --git a/h2gis-functions/src/main/java/org/h2gis/functions/io/gpx/model/AbstractGpxParserDefault.java b/h2gis-functions/src/main/java/org/h2gis/functions/io/gpx/model/AbstractGpxParserDefault.java index e3474707eb..b0df82a0b5 100644 --- a/h2gis-functions/src/main/java/org/h2gis/functions/io/gpx/model/AbstractGpxParserDefault.java +++ b/h2gis-functions/src/main/java/org/h2gis/functions/io/gpx/model/AbstractGpxParserDefault.java @@ -145,7 +145,7 @@ public boolean read(String tableName, ProgressVisitor progress) throws SQLExcept GPXTablesFactory.dropOSMTables(connection, isH2, requestedTable); } if (fileName.length() == 0) { - JDBCUtilities.createEmptyTable(connection, requestedTable.toString()); + JDBCUtilities.createEmptyTable(connection, requestedTable.toString(isH2)); } else { String table = requestedTable.getTable(); diff --git a/h2gis-functions/src/main/java/org/h2gis/functions/io/gpx/model/GPXTablesFactory.java b/h2gis-functions/src/main/java/org/h2gis/functions/io/gpx/model/GPXTablesFactory.java index 75836083db..3b4ef53f6a 100644 --- a/h2gis-functions/src/main/java/org/h2gis/functions/io/gpx/model/GPXTablesFactory.java +++ b/h2gis-functions/src/main/java/org/h2gis/functions/io/gpx/model/GPXTablesFactory.java @@ -308,7 +308,7 @@ public static PreparedStatement createTrackPointsTable(Connection connection, St * @throws SQLException */ public static void dropOSMTables(Connection connection, boolean isH2, TableLocation tablePrefix) throws SQLException { - String gpxTableName = tablePrefix.toString(); + String gpxTableName = tablePrefix.toString(isH2); String[] gpxTables = new String[]{WAYPOINT,ROUTE,ROUTEPOINT, TRACK, TRACKPOINT, TRACKSEGMENT}; StringBuilder sb = new StringBuilder("drop table if exists "); String gpxTableSuffix = gpxTables[0]; diff --git a/h2gis-functions/src/main/java/org/h2gis/functions/io/shp/SHPDriverFunction.java b/h2gis-functions/src/main/java/org/h2gis/functions/io/shp/SHPDriverFunction.java index 8758596431..2cc03536f4 100644 --- a/h2gis-functions/src/main/java/org/h2gis/functions/io/shp/SHPDriverFunction.java +++ b/h2gis-functions/src/main/java/org/h2gis/functions/io/shp/SHPDriverFunction.java @@ -278,8 +278,8 @@ public void importFile(Connection connection, String tableReference, File fileNa final TableLocation parse; int srid; try ( - // Build CREATE TABLE sql request - Statement st = connection.createStatement()) { + // Build CREATE TABLE sql request + Statement st = connection.createStatement()) { String types = DBFDriverFunction.getSQLColumnTypes(dbfHeader, isH2); if (!types.isEmpty()) { types = ", " + types; diff --git a/h2gis-functions/src/main/java/org/h2gis/functions/io/shp/SHPRead.java b/h2gis-functions/src/main/java/org/h2gis/functions/io/shp/SHPRead.java index 54c3ebccb3..ccc3da3128 100644 --- a/h2gis-functions/src/main/java/org/h2gis/functions/io/shp/SHPRead.java +++ b/h2gis-functions/src/main/java/org/h2gis/functions/io/shp/SHPRead.java @@ -27,7 +27,6 @@ import org.h2gis.api.AbstractFunction; import org.h2gis.api.EmptyProgressVisitor; import org.h2gis.api.ScalarFunction; -import org.h2gis.functions.io.utility.FileUtil; import org.h2gis.utilities.TableLocation; import org.h2gis.utilities.URIUtilities; diff --git a/h2gis-functions/src/main/java/org/h2gis/functions/io/tsv/TSVDriverFunction.java b/h2gis-functions/src/main/java/org/h2gis/functions/io/tsv/TSVDriverFunction.java index d59381a6b6..3afdfb0a22 100644 --- a/h2gis-functions/src/main/java/org/h2gis/functions/io/tsv/TSVDriverFunction.java +++ b/h2gis-functions/src/main/java/org/h2gis/functions/io/tsv/TSVDriverFunction.java @@ -141,7 +141,7 @@ public void exportTable(Connection connection, String tableReference, File fileN new ZipOutputStream(new FileOutputStream(fileName))))) { try (Statement st = connection.createStatement()) { JDBCUtilities.attachCancelResultSet(st, progress); - exportFromResultSet(connection, st.executeQuery(tableReference), bw, encoding, new EmptyProgressVisitor()); + exportFromResultSet(connection, st.executeQuery(location.toString(isH2)), bw, encoding, new EmptyProgressVisitor()); } } } else { @@ -161,7 +161,7 @@ public void exportTable(Connection connection, String tableReference, File fileN try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName)))) { try (Statement st = connection.createStatement()) { JDBCUtilities.attachCancelResultSet(st, progress); - exportFromResultSet(connection, st.executeQuery("SELECT * FROM " + location.toString()), bw, encoding, new EmptyProgressVisitor()); + exportFromResultSet(connection, st.executeQuery("SELECT * FROM " + location.toString(isH2)), bw, encoding, new EmptyProgressVisitor()); } } } else if (FileUtil.isExtensionWellFormated(fileName, "gz")) { @@ -174,7 +174,7 @@ public void exportTable(Connection connection, String tableReference, File fileN new GZIPOutputStream(new FileOutputStream(fileName))))) { try (Statement st = connection.createStatement()) { JDBCUtilities.attachCancelResultSet(st, progress); - exportFromResultSet(connection, st.executeQuery("SELECT * FROM " + location.toString()), bw, encoding, new EmptyProgressVisitor()); + exportFromResultSet(connection, st.executeQuery("SELECT * FROM " + location.toString(isH2)), bw, encoding, new EmptyProgressVisitor()); } } } else if (FileUtil.isExtensionWellFormated(fileName, "zip")) { @@ -187,7 +187,7 @@ public void exportTable(Connection connection, String tableReference, File fileN new ZipOutputStream(new FileOutputStream(fileName))))) { try (Statement st = connection.createStatement()) { JDBCUtilities.attachCancelResultSet(st, progress); - exportFromResultSet(connection, st.executeQuery("SELECT * FROM " + location.toString()), bw, encoding, new EmptyProgressVisitor()); + exportFromResultSet(connection, st.executeQuery("SELECT * FROM " + location.toString(isH2)), bw, encoding, new EmptyProgressVisitor()); } } } else { diff --git a/h2gis-functions/src/main/java/org/h2gis/functions/spatial/convert/ST_PolyFromWKB.java b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/convert/ST_PolyFromWKB.java index 09d548af6c..d87a2a9dbf 100644 --- a/h2gis-functions/src/main/java/org/h2gis/functions/spatial/convert/ST_PolyFromWKB.java +++ b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/convert/ST_PolyFromWKB.java @@ -23,10 +23,7 @@ import org.h2.value.ValueGeometry; import org.h2gis.api.DeterministicScalarFunction; import org.h2gis.utilities.GeometryTypeCodes; -import org.h2gis.utilities.GeometryMetaData; import org.locationtech.jts.geom.Geometry; -import org.locationtech.jts.io.ParseException; -import org.locationtech.jts.io.WKBReader; import java.io.IOException; import java.sql.SQLException; diff --git a/h2gis-functions/src/test/java/org/h2gis/functions/io/asc/AscReaderDriverTest.java b/h2gis-functions/src/test/java/org/h2gis/functions/io/asc/AscReaderDriverTest.java index 4bd3ad93e2..5959f79bc3 100644 --- a/h2gis-functions/src/test/java/org/h2gis/functions/io/asc/AscReaderDriverTest.java +++ b/h2gis-functions/src/test/java/org/h2gis/functions/io/asc/AscReaderDriverTest.java @@ -22,22 +22,30 @@ import org.h2gis.api.EmptyProgressVisitor; import org.h2gis.functions.factory.H2GISDBFactory; +import org.h2gis.postgis_jts_osgi.DataSourceFactoryImpl; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import java.io.File; import java.io.IOException; -import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import java.util.Properties; + import org.h2gis.unitTest.GeometryAsserts; import org.h2gis.utilities.JDBCUtilities; +import org.osgi.service.jdbc.DataSourceFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.sql.DataSource; import static org.junit.jupiter.api.Assertions.*; @@ -45,6 +53,9 @@ public class AscReaderDriverTest { private Connection connection; private static final String DB_NAME = "ASCRead_db"; + + private static final Logger log = LoggerFactory.getLogger(AscReaderDriverTest.class); + @BeforeEach public void tearUp() throws Exception { connection = JDBCUtilities.wrapConnection(H2GISDBFactory.createSpatialDataBase("/tmp/dbgis;AUTO_SERVER=TRUE", true, "")); @@ -211,17 +222,13 @@ public void testReadPrecipEnvelope() throws IOException, SQLException { reader.setExtractEnvelope(new Envelope(-178.242, -174.775, -89.707, -85.205)); reader.setDeleteTable(true); reader.read(connection, new File(AscReaderDriverTest.class.getResource("precip30min.asc").getPath()), new EmptyProgressVisitor(), "PRECIP30MIN", 4326); - - // Check database content - // Check number of extracted cells Statement st = connection.createStatement(); try(ResultSet rs = st.executeQuery("SELECT COUNT(*) CPT FROM PRECIP30MIN")) { assertTrue(rs.next()); assertEquals(90, rs.getInt("CPT")); } - } @Test @@ -230,8 +237,6 @@ public void testReadPrecipDownscale() throws IOException, SQLException { reader.setDownScale(5); reader.setDeleteTable(true); reader.read(connection, new File(AscReaderDriverTest.class.getResource("precip30min.asc").getPath()), new EmptyProgressVisitor(), "PRECIP30MIN", 4326); - - // Check database content // Check number of extracted cells @@ -270,9 +275,6 @@ public void testASCRead() throws IOException, SQLException { assertTrue(rs.next()); assertEquals(90, rs.getInt("CPT")); } - - - st.execute("DROP TABLE PRECIP30MIN IF EXISTS"); st.execute(String.format("CALL ASCREAD('%s', 'PRECIP30MIN', NULL, 5, TRUE)",AscReaderDriverTest.class.getResource("precip30min.asc").getFile())); @@ -293,4 +295,35 @@ public void testASCReadPoints() throws IOException, SQLException { GeometryAsserts.assertGeometryEquals("SRID=3857;POINT Z (-179.75 -80.25 234)", rs.getObject("THE_GEOM")); } } + + @Test + public void testReadPrecipEnvelopePOSTGIS(TestInfo testInfo) throws IOException, SQLException { + String url = "jdbc:postgresql://localhost:5432/orbisgis_db"; + Properties props = new Properties(); + props.setProperty("user", "orbisgis"); + props.setProperty("password", "orbisgis"); + props.setProperty("url", url); + DataSourceFactory dataSourceFactory = new DataSourceFactoryImpl(); + Connection con = null; + try { + DataSource ds = dataSourceFactory.createDataSource(props); + con = ds.getConnection(); + + } catch (SQLException e) { + log.warn("Cannot connect to the database to execute the test " + testInfo.getDisplayName()); + } + if (con != null) { + AscReaderDriver reader = new AscReaderDriver(); + reader.setExtractEnvelope(new Envelope(-178.242, -174.775, -89.707, -85.205)); + reader.setDeleteTable(true); + reader.read(con, new File(AscReaderDriverTest.class.getResource("precip30min.asc").getPath()), new EmptyProgressVisitor(), "PRECIP30MIN", 4326); + // Check database content + // Check number of extracted cells + Statement st = con.createStatement(); + try (ResultSet rs = st.executeQuery("SELECT COUNT(*) CPT FROM PRECIP30MIN")) { + assertTrue(rs.next()); + assertEquals(90, rs.getInt("CPT")); + } + } + } } \ No newline at end of file diff --git a/h2gis-functions/src/test/java/org/h2gis/functions/io/cvs/CSVDriverTest.java b/h2gis-functions/src/test/java/org/h2gis/functions/io/cvs/CSVDriverTest.java index 677f376eb1..e2bde52bf4 100644 --- a/h2gis-functions/src/test/java/org/h2gis/functions/io/cvs/CSVDriverTest.java +++ b/h2gis-functions/src/test/java/org/h2gis/functions/io/cvs/CSVDriverTest.java @@ -24,14 +24,20 @@ import org.h2gis.api.EmptyProgressVisitor; import org.h2gis.functions.factory.H2GISDBFactory; import org.h2gis.functions.io.csv.CSVDriverFunction; +import org.h2gis.postgis_jts_osgi.DataSourceFactoryImpl; import org.junit.jupiter.api.*; +import org.osgi.service.jdbc.DataSourceFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import javax.sql.DataSource; import java.io.File; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import java.util.Properties; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -47,6 +53,8 @@ public class CSVDriverTest { private static final String DB_NAME = "CSVImportExportTest"; private Statement st; + private static final Logger log = LoggerFactory.getLogger(CSVDriverTest.class); + @BeforeAll public static void tearUp() throws Exception { // Keep a connection alive to not close the DataBase on each unit test @@ -146,4 +154,42 @@ public void testDriverQueryOptions() throws SQLException, IOException { assertEquals(3,rs.getDouble(1),1e-2); } } + + @Test + public void testDriverDeleteTablePOSTGIS(TestInfo testInfo) throws SQLException, IOException { + String url = "jdbc:postgresql://localhost:5432/orbisgis_db"; + Properties props = new Properties(); + props.setProperty("user", "orbisgis"); + props.setProperty("password", "orbisgis"); + props.setProperty("url", url); + DataSourceFactory dataSourceFactory = new DataSourceFactoryImpl(); + Connection con = null; + try { + DataSource ds = dataSourceFactory.createDataSource(props); + con = ds.getConnection(); + + } catch (SQLException e) { + log.warn("Cannot connect to the database to execute the test " + testInfo.getDisplayName()); + } + if (con != null) { + Statement stat = con.createStatement(); + stat.execute("DROP TABLE IF EXISTS AREA, MYCSV"); + stat.execute("create table area(the_geom GEOMETRY, idarea int primary key)"); + stat.execute("insert into area values('POLYGON ((-10 109, 90 109, 90 9, -10 9, -10 109))', 1)"); + stat.execute("insert into area values('POLYGON ((90 109, 190 109, 190 9, 90 9, 90 109))', 2)"); + stat.execute("CREATE TABLE MYCSV(the_geom GEOMETRY, idarea int primary key)"); + // Export in target with special chars + File csvFile = new File("target/area éxport.csv"); + DriverFunction exp = new CSVDriverFunction(); + exp.exportTable(con, "AREA", csvFile, new EmptyProgressVisitor()); + exp.importFile(con, "MYCSV", csvFile, true, new EmptyProgressVisitor()); + ResultSet rs = stat.executeQuery("select SUM(idarea::int) from mycsv"); + try { + assertTrue(rs.next()); + assertEquals(3, rs.getDouble(1), 1e-2); + } finally { + rs.close(); + } + } + } } diff --git a/h2gis-functions/src/test/java/org/h2gis/functions/io/dbf/DBFImportExportTest.java b/h2gis-functions/src/test/java/org/h2gis/functions/io/dbf/DBFImportExportTest.java index 8bb91dbf3e..b7c0f32173 100644 --- a/h2gis-functions/src/test/java/org/h2gis/functions/io/dbf/DBFImportExportTest.java +++ b/h2gis-functions/src/test/java/org/h2gis/functions/io/dbf/DBFImportExportTest.java @@ -29,22 +29,31 @@ import org.h2gis.functions.io.dbf.internal.DBFDriver; import org.h2gis.functions.io.file_table.H2TableIndex; import org.h2gis.functions.io.shp.SHPEngineTest; +import org.h2gis.postgis_jts_osgi.DataSourceFactoryImpl; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; +import org.osgi.service.jdbc.DataSourceFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import javax.sql.DataSource; import java.io.File; import java.io.IOException; import java.sql.*; +import java.util.Properties; import static org.junit.jupiter.api.Assertions.*; /** * @author Nicolas Fortin + * @author Erwan Bocher, CNRS, 2020 */ public class DBFImportExportTest { private static Connection connection; private static final String DB_NAME = "DBFImportExportTest"; + private static final Logger log = LoggerFactory.getLogger(DBFImportExportTest.class); @BeforeAll public static void tearUp() throws Exception { @@ -253,4 +262,43 @@ public void testWriteReadEmptyTable2() throws SQLException { assertTrue(!res.next()); stat.close(); } + + @Test + public void testWriteReadEmptyTablePOSTGIS(TestInfo testInfo) throws SQLException, IOException { + String url = "jdbc:postgresql://localhost:5432/orbisgis_db"; + Properties props = new Properties(); + props.setProperty("user", "orbisgis"); + props.setProperty("password", "orbisgis"); + props.setProperty("url", url); + DataSourceFactory dataSourceFactory = new DataSourceFactoryImpl(); + Connection con = null; + try { + DataSource ds = dataSourceFactory.createDataSource(props); + con = ds.getConnection(); + + } catch (SQLException e) { + log.warn("Cannot connect to the database to execute the test " + testInfo.getDisplayName()); + } + if (con != null) { + Statement stat = con.createStatement(); + stat.execute("DROP TABLE IF EXISTS dbf_postgis"); + stat.execute("create table dbf_postgis(idarea int primary key, val DOUBLE PRECISION, descr CHAR(50))"); + stat.execute("insert into dbf_postgis values(1, 4.9406564584124654, 'main area')"); + stat.execute("insert into dbf_postgis values(2, 2.2250738585072009, 'second area')"); + // Create a dbf file using table area + DBFDriverFunction dbfDriverFunction = new DBFDriverFunction(); + dbfDriverFunction.exportTable(con, "dbf_postgis", new File("target/area_export.dbf"), true, new EmptyProgressVisitor()); + dbfDriverFunction.importFile(con, "dbf_postgis_imported", new File("target/area_export.dbf"), true, new EmptyProgressVisitor()); + + ResultSet res = stat.executeQuery("SELECT * FROM dbf_postgis_imported"); + assertTrue(res.next()); + assertEquals(1, res.getInt("idarea")); + assertEquals(4.9406564584124654, res.getDouble("val"), 0.001); + assertEquals("main area", res.getString("descr")); + assertTrue(res.next()); + assertEquals(2, res.getInt("idarea")); + assertEquals(2.2250738585072009, res.getDouble("val"), 0.001); + assertEquals("second area", res.getString("descr")); + } + } } diff --git a/h2gis-functions/src/test/java/org/h2gis/functions/io/geojson/GeojsonImportExportTest.java b/h2gis-functions/src/test/java/org/h2gis/functions/io/geojson/GeojsonImportExportTest.java index 0adc39ea46..fb1de154e2 100644 --- a/h2gis-functions/src/test/java/org/h2gis/functions/io/geojson/GeojsonImportExportTest.java +++ b/h2gis-functions/src/test/java/org/h2gis/functions/io/geojson/GeojsonImportExportTest.java @@ -25,16 +25,24 @@ import org.h2gis.api.EmptyProgressVisitor; import org.h2gis.functions.factory.H2GISDBFactory; import org.h2gis.functions.factory.H2GISFunctions; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; +import org.h2gis.postgis_jts_osgi.DataSourceFactoryImpl; +import org.junit.jupiter.api.*; +import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.io.WKTReader; import java.io.File; import java.io.IOException; +import java.nio.file.Files; import java.sql.*; +import java.util.Properties; + import org.h2gis.unitTest.GeometryAsserts; +import org.osgi.service.jdbc.DataSourceFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.sql.DataSource; import static org.junit.jupiter.api.Assertions.*; @@ -48,6 +56,7 @@ public class GeojsonImportExportTest { private static Connection connection; private static final String DB_NAME = "GeojsonExportTest"; private static final WKTReader WKTREADER = new WKTReader(); + private static final Logger log = LoggerFactory.getLogger(GeojsonImportExportTest.class); @BeforeAll public static void tearUp() throws Exception { @@ -78,6 +87,19 @@ public void testGeojsonPoint() throws Exception { } } + @Test + public void testGeojsonPointZ() throws Exception { + try (Statement stat = connection.createStatement()) { + stat.execute("DROP TABLE IF EXISTS TABLE_POINT"); + stat.execute("create table TABLE_POINT(idarea int primary key, the_geom GEOMETRY(POINTZ))"); + stat.execute("insert into TABLE_POINT values(1, 'POINT(1 2 3)')"); + ResultSet res = stat.executeQuery("SELECT ST_AsGeoJSON(the_geom) from TABLE_POINT;"); + res.next(); + assertEquals("{\"type\":\"Point\",\"coordinates\":[1.0,2.0,3.0]}", res.getString(1)); + res.close(); + } + } + @Test public void testGeojsonLineString() throws Exception { try (Statement stat = connection.createStatement()) { @@ -214,6 +236,26 @@ public void testWriteReadGeojsonPoint() throws Exception { } } + @Test + public void testWriteReadGeojsonPointZ() throws Exception { + try (Statement stat = connection.createStatement()) { + stat.execute("DROP TABLE IF EXISTS TABLE_POINTS"); + stat.execute("DROP TABLE IF EXISTS TABLE_POINTS_READ"); + stat.execute("create table TABLE_POINTS(the_geom GEOMETRY(POINTZ))"); + stat.execute("insert into TABLE_POINTS values( 'POINT(1 2 3)')"); + stat.execute("insert into TABLE_POINTS values( 'POINT(10 200 2000)')"); + stat.execute("CALL GeoJsonWrite('target/points.geojson', 'TABLE_POINTS');"); + stat.execute("CALL GeoJsonRead('target/points.geojson', 'TABLE_POINTS_READ');"); + ResultSet res = stat.executeQuery("SELECT * FROM TABLE_POINTS_READ;"); + res.next(); + assertEquals(3,((Geometry) res.getObject(1)).getCoordinate().getZ()); + res.next(); + assertEquals(2000,((Geometry) res.getObject(1)).getCoordinate().getZ());; + res.close(); + stat.execute("DROP TABLE IF EXISTS TABLE_POINTS_READ"); + } + } + @Test public void testWriteReadGeojsonPointProperties() throws Exception { Statement stat = connection.createStatement(); @@ -1013,5 +1055,60 @@ public void testReadWithNullValues() throws Exception { assertEquals("java.lang.Long", metaData.getColumnClassName(11)); assertEquals("java.lang.Double", metaData.getColumnClassName(12)); } + + + @Test + public void exportImportPointPostGIS(TestInfo testInfo) throws IOException, SQLException { + String url = "jdbc:postgresql://localhost:5432/orbisgis_db"; + Properties props = new Properties(); + props.setProperty("user", "orbisgis"); + props.setProperty("password", "orbisgis"); + props.setProperty("url", url); + DataSourceFactory dataSourceFactory = new DataSourceFactoryImpl(); + Connection con= null; + try { + DataSource ds = dataSourceFactory.createDataSource(props); + con = ds.getConnection(); + + } catch (SQLException e) { + log.warn("Cannot connect to the database to execute the test "+ testInfo.getDisplayName()); + } + if(con!=null){ + Statement stat = con.createStatement(); + File ouputFile = new File("target/punctual_export_postgis.geojson"); + Files.deleteIfExists(ouputFile.toPath()); + stat.execute("DROP TABLE IF EXISTS PUNCTUAL"); + stat.execute("create table punctual(idarea int primary key, the_geom GEOMETRY(POINTZ, 4326))"); + stat.execute("insert into punctual values(1, ST_GEOMFROMTEXT('POINT(-10 109 5)',4326))"); + // Create a shape file using table area + GeoJsonDriverFunction driver = new GeoJsonDriverFunction(); + driver.exportTable(con,"punctual", ouputFile,new EmptyProgressVisitor()); + // Read this shape file to check values + assertTrue(ouputFile.exists()); + stat.execute("DROP TABLE IF EXISTS IMPORT_PUNCTUAL;"); + driver.importFile(con, "IMPORT_PUNCTUAL", ouputFile, true, new EmptyProgressVisitor()); + ResultSet res = stat.executeQuery("SELECT THE_GEOM FROM IMPORT_PUNCTUAL;"); + res.next(); + Geometry geom = (Geometry) res.getObject(1); + assertEquals(4326, geom.getSRID()); + Coordinate coord = geom.getCoordinate(); + assertEquals(coord.z, 5, 10E-1); + stat.execute("DROP TABLE IF EXISTS IMPORT_PUNCTUAL;"); + res.close(); + } + } + + @Test + public void testSelectWrite() throws Exception { + try (Statement stat = connection.createStatement()) { + stat.execute("CALL GeoJsonWrite('target/lines.geojson', '(SELECT ST_GEOMFROMTEXT(''LINESTRING(1 10, 20 15)'', 4326) as the_geom)');"); + stat.execute("CALL GeoJsonRead('target/lines.geojson', 'TABLE_LINESTRINGS_READ');"); + ResultSet res = stat.executeQuery("SELECT * FROM TABLE_LINESTRINGS_READ;"); + res.next(); + GeometryAsserts.assertGeometryEquals("LINESTRING(1 10, 20 15)", res.getString("THE_GEOM")); + res.close(); + stat.execute("DROP TABLE IF EXISTS TABLE_LINESTRINGS_READ"); + } + } } diff --git a/h2gis-functions/src/test/java/org/h2gis/functions/io/gpx/GPXImportTest.java b/h2gis-functions/src/test/java/org/h2gis/functions/io/gpx/GPXImportTest.java index 56157b4ea7..0765feb546 100644 --- a/h2gis-functions/src/test/java/org/h2gis/functions/io/gpx/GPXImportTest.java +++ b/h2gis-functions/src/test/java/org/h2gis/functions/io/gpx/GPXImportTest.java @@ -22,15 +22,24 @@ import org.h2.jdbc.JdbcSQLException; import org.h2.util.StringUtils; +import org.h2gis.api.EmptyProgressVisitor; import org.h2gis.functions.factory.H2GISDBFactory; import org.h2gis.functions.factory.H2GISFunctions; +import org.h2gis.postgis_jts_osgi.DataSourceFactoryImpl; import org.junit.jupiter.api.*; import org.locationtech.jts.geom.Geometry; +import org.osgi.service.jdbc.DataSourceFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import javax.sql.DataSource; +import java.io.File; +import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import java.util.Properties; import static org.junit.jupiter.api.Assertions.*; @@ -43,6 +52,7 @@ public class GPXImportTest { private static Connection connection; private static final String DB_NAME = "GPXImportTest"; private Statement st; + private static final Logger log = LoggerFactory.getLogger(GPXImportTest.class); @BeforeAll public static void tearUp() throws Exception { @@ -245,4 +255,41 @@ public void importGPXFileTableName() throws SQLException { assertEquals(4326, ((Geometry)rs.getObject("the_geom")).getSRID()); rs.close(); } + + @Test + public void importGPXWaypointsPOSTGIS(TestInfo testInfo) throws IOException, SQLException { + String url = "jdbc:postgresql://localhost:5432/orbisgis_db"; + Properties props = new Properties(); + props.setProperty("user", "orbisgis"); + props.setProperty("password", "orbisgis"); + props.setProperty("url", url); + DataSourceFactory dataSourceFactory = new DataSourceFactoryImpl(); + Connection con= null; + try { + DataSource ds = dataSourceFactory.createDataSource(props); + con = ds.getConnection(); + + } catch (SQLException e) { + log.warn("Cannot connect to the database to execute the test "+ testInfo.getDisplayName()); + } + if(con!=null) { + Statement statement = con.createStatement(); + GPXDriverFunction gpxDriverFunction = new GPXDriverFunction(); + gpxDriverFunction.importFile(con, "gpxdata", new File(GPXImportTest.class.getResource("waypoint.gpx").getPath()), true, new EmptyProgressVisitor()); + ResultSet rs = statement.executeQuery("SELECT * FROM gpxdata_waypoint limit 1"); + assertTrue(rs.next()); + rs.close(); + // Check number + rs = statement.executeQuery("SELECT count(id) FROM gpxdata_waypoint"); + rs.next(); + assertTrue(rs.getInt(1) == 3); + rs.close(); + // Check content + rs = statement.executeQuery("SELECT * FROM gpxdata_waypoint"); + assertTrue(rs.next()); + assertEquals("POINT (-71.119277 42.438878)", rs.getString("the_geom")); + assertEquals(4326, ((Geometry) rs.getObject("the_geom")).getSRID()); + rs.close(); + } + } } diff --git a/h2gis-functions/src/test/java/org/h2gis/functions/io/shp/SHPImportExportTest.java b/h2gis-functions/src/test/java/org/h2gis/functions/io/shp/SHPImportExportTest.java index 346a565a79..f6962282dd 100644 --- a/h2gis-functions/src/test/java/org/h2gis/functions/io/shp/SHPImportExportTest.java +++ b/h2gis-functions/src/test/java/org/h2gis/functions/io/shp/SHPImportExportTest.java @@ -32,10 +32,7 @@ import org.h2gis.functions.io.file_table.H2TableIndex; import org.h2gis.functions.io.shp.internal.SHPDriver; import org.h2gis.postgis_jts_osgi.DataSourceFactoryImpl; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.*; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.io.WKTWriter; @@ -51,6 +48,8 @@ import org.h2gis.unitTest.GeometryAsserts; import org.osgi.service.jdbc.DataSourceFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.sql.DataSource; @@ -64,6 +63,8 @@ public class SHPImportExportTest { private static Connection connection; private static final String DB_NAME = "SHPImportTest"; + private static final Logger log = LoggerFactory.getLogger(SHPImportExportTest.class); + @BeforeAll public static void tearUp() throws Exception { // Keep a connection alive to not close the DataBase on each unit test @@ -800,65 +801,79 @@ public void testSelectWriteRead2() throws Exception { } } - @Disabled @Test - public void exportImportPointPostGIS() throws SQLException, IOException { - String url = "jdbc:postgresql://host:port/dbname"; + public void exportImportPointPostGIS(TestInfo testInfo) throws SQLException, IOException { + String url = "jdbc:postgresql://localhost:5432/orbisgis_db"; Properties props = new Properties(); - props.setProperty("user", ""); - props.setProperty("password", ""); + props.setProperty("user", "orbisgis"); + props.setProperty("password", "orbisgis"); props.setProperty("url", url); DataSourceFactory dataSourceFactory = new DataSourceFactoryImpl(); - DataSource ds = dataSourceFactory.createDataSource(props); - Connection con = ds.getConnection(); - Statement stat = con.createStatement(); - File shpFile = new File("target/punctual_export_postgis.shp"); - Files.deleteIfExists(shpFile.toPath()); - stat.execute("DROP TABLE IF EXISTS PUNCTUAL"); - stat.execute("create table punctual(idarea int primary key, the_geom GEOMETRY(POINTZ, 4326))"); - stat.execute("insert into punctual values(1, ST_GEOMFROMTEXT('POINT(-10 109 5)',4326))"); - // Create a shape file using table area - SHPDriverFunction driver = new SHPDriverFunction(); - driver.exportTable(con,"punctual", shpFile,new EmptyProgressVisitor()); - // Read this shape file to check values - assertTrue(shpFile.exists()); - stat.execute("DROP TABLE IF EXISTS IMPORT_PUNCTUAL;"); - driver.importFile(con, "IMPORT_PUNCTUAL", shpFile, true, new EmptyProgressVisitor()); - ResultSet res = stat.executeQuery("SELECT THE_GEOM FROM IMPORT_PUNCTUAL;"); - res.next(); - Geometry geom = (Geometry) res.getObject(1); - assertEquals(4326, geom.getSRID()); - Coordinate coord = geom.getCoordinate(); - assertEquals(coord.z, 5, 10E-1); - stat.execute("DROP TABLE IF EXISTS IMPORT_PUNCTUAL;"); - res.close(); + Connection con= null; + try { + DataSource ds = dataSourceFactory.createDataSource(props); + con = ds.getConnection(); + + } catch (SQLException e) { + log.warn("Cannot connect to the database to execute the test "+ testInfo.getDisplayName()); + } + if(con!=null) { + Statement stat = con.createStatement(); + File shpFile = new File("target/punctual_export_postgis.shp"); + Files.deleteIfExists(shpFile.toPath()); + stat.execute("DROP TABLE IF EXISTS PUNCTUAL"); + stat.execute("create table punctual(idarea int primary key, the_geom GEOMETRY(POINTZ, 4326))"); + stat.execute("insert into punctual values(1, ST_GEOMFROMTEXT('POINT(-10 109 5)',4326))"); + // Create a shape file using table area + SHPDriverFunction driver = new SHPDriverFunction(); + driver.exportTable(con, "punctual", shpFile, new EmptyProgressVisitor()); + // Read this shape file to check values + assertTrue(shpFile.exists()); + stat.execute("DROP TABLE IF EXISTS IMPORT_PUNCTUAL;"); + driver.importFile(con, "IMPORT_PUNCTUAL", shpFile, true, new EmptyProgressVisitor()); + ResultSet res = stat.executeQuery("SELECT THE_GEOM FROM IMPORT_PUNCTUAL;"); + res.next(); + Geometry geom = (Geometry) res.getObject(1); + assertEquals(4326, geom.getSRID()); + Coordinate coord = geom.getCoordinate(); + assertEquals(coord.z, 5, 10E-1); + stat.execute("DROP TABLE IF EXISTS IMPORT_PUNCTUAL;"); + res.close(); + } } - @Disabled @Test - public void testSelectWriteReadPostGIS() throws Exception { - String url = "jdbc:postgresql://?/?"; + public void testSelectWriteReadPostGIS(TestInfo testInfo) throws Exception { + String url = "jdbc:postgresql://localhost:5432/orbisgis_db"; Properties props = new Properties(); - props.setProperty("user", ""); - props.setProperty("password","" ); + props.setProperty("user", "orbisgis"); + props.setProperty("password", "orbisgis"); props.setProperty("url", url); DataSourceFactory dataSourceFactory = new DataSourceFactoryImpl(); - DataSource ds = dataSourceFactory.createDataSource(props); - Connection con = ds.getConnection(); - try (Statement stat = con.createStatement()) { - stat.execute(" DROP TABLE IF EXISTS orbisgis;"+ - "CREATE TABLE orbisgis (id int, the_geom geometry(point, 4326));"+ - "INSERT INTO orbisgis VALUES (1, ST_GEOMFROMTEXT('POINT(10 10)',4326)), (2, ST_GEOMFROMTEXT('POINT(1 1)',4326)); "); - SHPDriverFunction shpDriverFunction = new SHPDriverFunction(); - shpDriverFunction.exportTable(con,"(SELECT st_buffer(the_geom, 10) as the_geom from orbisgis)", new File("target/points.shp"), null, true , new EmptyProgressVisitor()); - shpDriverFunction.importFile(con,"TABLE_POINTS_READ", new File("target/points.shp"), null, true , new EmptyProgressVisitor()); - ResultSet res = stat.executeQuery("SELECT * FROM TABLE_POINTS_READ;"); - res.next(); - Geometry geom = (Geometry) res.getObject("THE_GEOM"); - assertEquals(4326, geom.getSRID()); - GeometryAsserts.assertGeometryEquals("SRID=4326;MULTIPOLYGON (((0 9.999999999999968, 0.1921471959676886 11.950903220161248, 0.761204674887118 13.826834323650864, 1.685303876974526 15.55570233019599, 2.928932188134495 17.071067811865447, 4.444297669803942 18.314696123025428, 6.173165676349064 19.238795325112854, 8.049096779838678 19.807852804032297, 9.999999999999963 20, 11.950903220161248 19.80785280403231, 13.826834323650868 19.238795325112882, 15.555702330195995 18.31469612302547, 17.071067811865454 17.071067811865497, 18.31469612302544 15.555702330196045, 19.23879532511286 13.826834323650921, 19.8078528040323 11.950903220161305, 20 10, 19.807852804032308 8.049096779838719, 19.238795325112868 6.173165676349106, 18.314696123025456 4.444297669803983, 17.071067811865483 2.9289321881345307, 15.55570233019603 1.6853038769745528, 13.826834323650909 0.7612046748871375, 11.950903220161296 0.19214719596769747, 10.000000000000016 0, 8.049096779838735 0.19214719596769214, 6.173165676349122 0.7612046748871251, 4.444297669803995 1.6853038769745368, 2.9289321881345405 2.9289321881345085, 1.6853038769745616 4.444297669803957, 0.7612046748871428 6.173165676349077, 0.19214719596770102 8.049096779838688, 0 9.999999999999968)))",geom); - res.close(); - stat.execute("DROP TABLE IF EXISTS TABLE_POINTS_READ"); + Connection con= null; + try { + DataSource ds = dataSourceFactory.createDataSource(props); + con = ds.getConnection(); + + } catch (SQLException e) { + log.warn("Cannot connect to the database to execute the test "+ testInfo.getDisplayName()); + } + if(con!=null) { + try (Statement stat = con.createStatement()) { + stat.execute(" DROP TABLE IF EXISTS orbisgis;" + + "CREATE TABLE orbisgis (id int, the_geom geometry(point, 4326));" + + "INSERT INTO orbisgis VALUES (1, ST_GEOMFROMTEXT('POINT(10 10)',4326)), (2, ST_GEOMFROMTEXT('POINT(1 1)',4326)); "); + SHPDriverFunction shpDriverFunction = new SHPDriverFunction(); + shpDriverFunction.exportTable(con, "(SELECT st_buffer(the_geom, 10) as the_geom from orbisgis)", new File("target/points.shp"), null, true, new EmptyProgressVisitor()); + shpDriverFunction.importFile(con, "TABLE_POINTS_READ", new File("target/points.shp"), null, true, new EmptyProgressVisitor()); + ResultSet res = stat.executeQuery("SELECT * FROM TABLE_POINTS_READ;"); + res.next(); + Geometry geom = (Geometry) res.getObject("THE_GEOM"); + assertEquals(4326, geom.getSRID()); + GeometryAsserts.assertGeometryEquals("SRID=4326;MULTIPOLYGON (((0 9.999999999999968, 0.1921471959676886 11.950903220161248, 0.761204674887118 13.826834323650864, 1.685303876974526 15.55570233019599, 2.928932188134495 17.071067811865447, 4.444297669803942 18.314696123025428, 6.173165676349064 19.238795325112854, 8.049096779838678 19.807852804032297, 9.999999999999963 20, 11.950903220161248 19.80785280403231, 13.826834323650868 19.238795325112882, 15.555702330195995 18.31469612302547, 17.071067811865454 17.071067811865497, 18.31469612302544 15.555702330196045, 19.23879532511286 13.826834323650921, 19.8078528040323 11.950903220161305, 20 10, 19.807852804032308 8.049096779838719, 19.238795325112868 6.173165676349106, 18.314696123025456 4.444297669803983, 17.071067811865483 2.9289321881345307, 15.55570233019603 1.6853038769745528, 13.826834323650909 0.7612046748871375, 11.950903220161296 0.19214719596769747, 10.000000000000016 0, 8.049096779838735 0.19214719596769214, 6.173165676349122 0.7612046748871251, 4.444297669803995 1.6853038769745368, 2.9289321881345405 2.9289321881345085, 1.6853038769745616 4.444297669803957, 0.7612046748871428 6.173165676349077, 0.19214719596770102 8.049096779838688, 0 9.999999999999968)))", geom); + res.close(); + stat.execute("DROP TABLE IF EXISTS TABLE_POINTS_READ"); + } } } diff --git a/h2gis-functions/src/test/java/org/h2gis/functions/io/tsv/TSVDriverTest.java b/h2gis-functions/src/test/java/org/h2gis/functions/io/tsv/TSVDriverTest.java index 1efc4f9255..63a6f121e9 100644 --- a/h2gis-functions/src/test/java/org/h2gis/functions/io/tsv/TSVDriverTest.java +++ b/h2gis-functions/src/test/java/org/h2gis/functions/io/tsv/TSVDriverTest.java @@ -25,17 +25,22 @@ import org.h2gis.api.EmptyProgressVisitor; import org.h2gis.functions.factory.H2GISDBFactory; import org.h2gis.functions.factory.H2GISFunctions; +import org.h2gis.postgis_jts_osgi.DataSourceFactoryImpl; import org.junit.jupiter.api.*; import java.io.File; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; import java.sql.*; +import java.util.Properties; + import org.h2gis.unitTest.GeometryAsserts; import static org.junit.jupiter.api.Assertions.*; -import org.locationtech.jts.geom.Geometry; +import org.osgi.service.jdbc.DataSourceFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.sql.DataSource; /** * @@ -47,6 +52,8 @@ public class TSVDriverTest { private static final String DB_NAME = "TSVImportExportTest"; private Statement st; + private static final Logger log = LoggerFactory.getLogger(TSVDriverTest.class); + @BeforeAll public static void tearUp() throws Exception { // Keep a connection alive to not close the DataBase on each unit test @@ -190,7 +197,7 @@ public void testWriteQueryRead() throws SQLException, IOException { } - @Test + @Test public void testSelectWriteReadTSVLinestring() throws Exception { try (Statement stat = connection.createStatement()) { stat.execute("DROP TABLE IF EXISTS TABLE_LINESTRINGS, TABLE_LINESTRINGS_READ"); @@ -206,18 +213,40 @@ public void testSelectWriteReadTSVLinestring() throws Exception { stat.execute("DROP TABLE IF EXISTS TABLE_LINESTRINGS_READ"); } } - + @Test - public void testSelectWrite() throws Exception { - try (Statement stat = connection.createStatement()) { - stat.execute("CALL GeoJsonWrite('target/lines.geojson', '(SELECT ST_GEOMFROMTEXT(''LINESTRING(1 10, 20 15)'', 4326) as the_geom)');"); - stat.execute("CALL GeoJsonRead('target/lines.geojson', 'TABLE_LINESTRINGS_READ');"); - ResultSet res = stat.executeQuery("SELECT * FROM TABLE_LINESTRINGS_READ;"); - res.next(); - GeometryAsserts.assertGeometryEquals("LINESTRING(1 10, 20 15)", res.getString("THE_GEOM")); - res.close(); - stat.execute("DROP TABLE IF EXISTS TABLE_LINESTRINGS_READ"); + public void testSelectWriteReadTSVLinestringPOSTGIS(TestInfo testInfo) throws Exception { + String url = "jdbc:postgresql://localhost:5432/orbisgis_db"; + Properties props = new Properties(); + props.setProperty("user", "orbisgis"); + props.setProperty("password", "orbisgis"); + props.setProperty("url", url); + DataSourceFactory dataSourceFactory = new DataSourceFactoryImpl(); + Connection con= null; + try { + DataSource ds = dataSourceFactory.createDataSource(props); + con = ds.getConnection(); + + } catch (SQLException e) { + log.warn("Cannot connect to the database to execute the test "+ testInfo.getDisplayName()); + } + if(con!=null) { + try (Statement stat = con.createStatement()) { + stat.execute("DROP TABLE IF EXISTS TABLE_LINESTRINGS, TABLE_LINESTRINGS_READ"); + stat.execute("create table TABLE_LINESTRINGS(the_geom GEOMETRY(LINESTRING), id int)"); + stat.execute("insert into TABLE_LINESTRINGS values( 'LINESTRING(1 10, 20 15)', 2)"); + TSVDriverFunction tsvDriverFunction = new TSVDriverFunction(); + tsvDriverFunction.exportTable(con, "table_linestrings", new File("target/lines_postgis.tsv"),true, new EmptyProgressVisitor()); + tsvDriverFunction.importFile(con, "table_linestrings_read", new File("target/lines_postgis.tsv"), true, new EmptyProgressVisitor()); + ResultSet res = stat.executeQuery("SELECT * FROM table_linestrings_read;"); + res.next(); + GeometryAsserts.assertGeometryEquals("LINESTRING(1 10, 20 15)", res.getString("THE_GEOM")); + res.close(); + stat.execute("DROP TABLE IF EXISTS TABLE_LINESTRINGS_READ"); + } } } + + } diff --git a/postgis-jts/pom.xml b/postgis-jts/pom.xml index 9762d3409a..818ee6ce05 100644 --- a/postgis-jts/pom.xml +++ b/postgis-jts/pom.xml @@ -41,6 +41,7 @@ net.postgis postgis-jdbc + 2.5.0 org.locationtech.jts