Skip to content

Instantly share code, notes, and snippets.

@justinlewis
Last active December 11, 2015 00:19
Show Gist options
  • Save justinlewis/4515556 to your computer and use it in GitHub Desktop.
Save justinlewis/4515556 to your computer and use it in GitHub Desktop.
Script for truncating and repopulating the geometry_columns table in a pre PostGIS 2.0 database.
##
## Script for truncating and repopulating the geometry_columns table in a pre PostGIS 2.0 database.
#### This is important because the geometry_columns table often has legacy records where tables have been deleted
#### but the corresponding geom record was not removed.
##
## This could be done as a PostgreSQL function with a trigger as well.
##
## Author = Justin Lewis
##
import pg
class table_cleanse:
def clear_geom_table(self, table):
print "Clearing all records from the geometry_columns table..."
clearTable = "TRUNCATE {table};".format(table = table)
conn.query(clearTable)
def iter_db_tables(self):
print "Repopulating the geometry_columns table..."
selectTables = "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' ORDER BY table_schema,table_name;"
tables = conn.query(selectTables)
table_list = tables.getresult()
for table in table_list:
table = self.strip_list_entries(table)
self.pop_geom(table)
def strip_list_entries(self, entry):
entry = str(entry)
entry = entry.lstrip("('")
entry = entry.rstrip("',)")
return entry
def pop_geom(self, table):
popGeom = "SELECT Populate_Geometry_Columns('public.{table}'::regclass);".format(table = table)
conn.query(popGeom)
print "Populated geom table for: ",table
if __name__ == '__main__':
#DB connection properties
conn = pg.connect(dbname = 'YOUR_DB', host= 'YOUR_HOST', port= 5432, user = 'YOUR_USER',passwd= 'YOUR_PASS')
table = 'geometry_columns' #### Change for testing!!!
table_cleanse = table_cleanse()
table_cleanse.clear_geom_table(table)
table_cleanse.iter_db_tables()
print ""
print "process complete!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment