Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
if self.logOutput is True:
self.__writeLog("Try to import data:")
self.__writeLog(createTableQuery)
self.cursor.execute(createTableQuery)
self.cursor.execute("SELECT COUNT (*) FROM " + output)
rows = self.cursor.fetchall()[0][0]
if rows == 0:
raise GrassPostGisImporterError("Query returned no results.")
addCommentQuery = "COMMENT ON TABLE " + output + " IS 'created with v.in.postgis.py'"
self.cursor.execute(addCommentQuery)
except GrassPostGisImporterError:
##no results
raise
except:
##query execution error
raise GrassPostGisImporterError("An error occurred during sql import. Check your connection \
to the database and your sql query.")
def getGeometryInfo(self, output, geometryfield):
"""Retrieve geometry parameters of the result.
We need to use the postgis AddGeometryColumn function so that v.in.ogr will work.
This method aims to retrieve necessary info for AddGeometryColumn to work.
Returns a dict with
"""
self.printMessage("Retrieving geometry info.")
##if there is more than one geometry type in the query result table, we use the
##generic GEOMETRY type
type="GEOMETRY"
self.cursor.execute("SELECT DISTINCT GeometryType(" + geometryfield + ") FROM " + output)
rows = self.cursor.fetchall()
if rows is not None and len(rows) == 1:
type = str(rows[0][0])
if rows is None or len(rows) == 0:
raise GrassPostGisImporterError("Unable to retrieve geometry type. Query result may have no geometry.")
##same thing with number of dimensions. If the query is syntactically correct but returns
##no geometry, this step will cause an error.
ndims = 0
self.cursor.execute("SELECT DISTINCT ndims(" + geometryfield + ") FROM " + output)
rows = self.cursor.fetchall()
if rows is not None and len(rows) == 1:
ndims = str(rows[0][0])
if self.logOutput is True:
self.__writeLog("ndims=" + ndims)
else:
raise GrassPostGisImporterError("unable to retrieve a unique coordinates dimension for \
this query or no geometry is present. Check your sql query.")
##srid
srid="-1"
self.cursor.execute("SELECT DISTINCT srid(" + geometryfield + ") FROM " + output)
rows = self.cursor.fetchall()
self.__writeLog("Found another geometry in the query result than selected one: "\
+ str(otherGeoColumn) + ". Column will be dropped.")
self.cursor.execute("ALTER TABLE " + output + " DROP COLUMN " + otherGeoColumn)
##we already inserted the geometry so we will recopy it in the newly created geometry column
if self.logOutput is True:
self.__writeLog("Create geometry column.")
self.cursor.execute("ALTER TABLE " + output + " RENAME COLUMN " + geometryField + " TO the_geom_tmp")
self.cursor.execute("SELECT AddGeometryColumn('', '" + output + "','" + geometryField + "',\
"+ geoParams['srid'] + ",'" + geoParams['type'] + "'," + geoParams['ndims'] + ");")
self.cursor.execute("UPDATE " + output + " SET " + geometryField + " = the_geom_tmp")
self.cursor.execute("ALTER TABLE " + output + " DROP COLUMN the_geom_tmp")
if addGistIndex is True:
self.cursor.execute("CREATE INDEX " + output + "_index ON " + output + " \
USING GIST (" + geometryField + " GIST_GEOMETRY_OPS);")
except:
raise GrassPostGisImporterError("An error occured during geometry insertion.")
def addCategory(self, output):
"""Add a category column in the result table.
With the pg driver (not the dbf one), v.in.ogr need a 'cat' column for index creation
if -d flag wasn't not selected, can't import if query result already have a cat column
todo : add cat_ column in this case, as v.in.ogr with dbf driver do
"""
try:
self.printMessage("Adding category column.")
s = "ALTER TABLE " + str(output) + " ADD COLUMN cat serial NOT NULL"
self.cursor.execute("ALTER TABLE " + str(output) + " ADD COLUMN cat serial NOT NULL")
tmp_pkey_name = "tmp_pkey_" + str(output)
self.cursor.execute("ALTER TABLE " + str(output) + " ADD CONSTRAINT " \
+ tmp_pkey_name + " PRIMARY KEY (cat)")
except:
raise GrassPostGisImporterError("Unable to add a 'cat' column. A column named 'CAT' \
or 'cat' may be present in your input data. \
This column is reserved for Grass to store categories.")
def createPostgresTableFromQuery(self, output, query):
"""Create a table in postgresql populated with results from the query, and tag it.
We will later be able to figure out if this table was created by the importer (see checkLayers())
"""
try:
createTableQuery = "CREATE TABLE " + str(output) + " AS " + str(query)
if self.logOutput is True:
self.__writeLog("Try to import data:")
self.__writeLog(createTableQuery)
self.cursor.execute(createTableQuery)
self.cursor.execute("SELECT COUNT (*) FROM " + output)
rows = self.cursor.fetchall()[0][0]
if rows == 0:
raise GrassPostGisImporterError("Query returned no results.")
addCommentQuery = "COMMENT ON TABLE " + output + " IS 'created with v.in.postgis.py'"
self.cursor.execute(addCommentQuery)
except GrassPostGisImporterError:
##no results
raise
except:
##query execution error
raise GrassPostGisImporterError("An error occurred during sql import. Check your connection \
to the database and your sql query.")
def checkLayers(self, output):
"""Test if the grass layer 'output' already exists.
Note : for this to work with grass6.3, in find_file function from core.py,
command should be (n flag removed because 6.4 specific):
s = read_command("g.findfile", element = element, file = name, mapset = mapset)
"""
self.printMessage("Check layers:")
##Test if output vector map already exists.
testOutput = grass.find_file(output, element = 'vector')
if testOutput['fullname'] != '':
if not grass.overwrite() is True:
raise GrassPostGisImporterError("Vector map " + output + " already exists in mapset search path. \
#Use the --o flag to overwrite.")
else:
self.printMessage("Vector map " + output + " will be overwritten.", type = 'warning')
return True