Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- ###########################################################################
- """Usage: gdb_to_pg.py -D <path> -H <host> -u <user> -w <password> -d <dbname>
- Options:
- -h, --help эта справка по работе с программой
- -H, --host хост БД, в которую конвертируются данные
- -u, --user имя пользователя для подключения к БД
- -w, --password пароль пользользователя, под которым происходит подключение
- -d, --dbname имя БД, в которую юудет производится импорт данных
- -p, --port порт для подключения к БД
- -D, --dir корневая директория для поиска файлов
- """
- __author__ = 'vladimir.rybalko@gmail.com (Vladimir Rybalko)'
- import os, sys, fnmatch, psycopg2, chardet
- from optparse import OptionParser
- try:
- from osgeo import ogr, osr, gdal
- except:
- sys.exit('ERROR: cannot find GDAL/OGR modules')
- def ParseInputs():
- parser = OptionParser()
- parser.add_option('-H', '--host', dest='host', default='localhost', help='The host name PG to connect.')
- parser.add_option('-u', '--user', dest='userName', default='postgres', help='The user to connect the PG.')
- parser.add_option('-w', '--password', dest='password', default='', help="The user's password")
- parser.add_option('-p', '--port', dest='port', default='5432', help='The port to connect the PG')
- parser.add_option('-d', '--dbname', dest='databaseName', default='postgres', help='The database name to connect the PG')
- parser.add_option('-D','--dir', dest='dir', help='The root directory for find files')
- (options, args) = parser.parse_args()
- if args:
- parser.print_help()
- parser.exit(msg='\nUnexpected arguments: %s\n' % ' '.join(args))
- invalid_args = False
- if options.host is None:
- print ('-H (host) is required')
- invalid_args = True
- if options.userName is None:
- print ('-u (userName) is required')
- invalid_args = True
- if options.password is None:
- print ('-w (password) is required')
- invalid_args = True
- if options.databaseName is None:
- print ('-d (dbname) is required')
- invalid_args = True
- if options.dir is None or os.path.isdir(options.dir) is False:
- print ('-D (dir) задан не задан или задан не правильно')
- invalid_args = True
- if invalid_args:
- sys.exit(4)
- return options
- def connect(options):
- try:
- client = psycopg2.connect("dbname='%s' user='%s' host='%s' password='%s'" % (options.databaseName, options.userName, options.host, options.password))
- except:
- #print ("I am unable to connect to the database")
- sys.exit('I am unable to connect to the database')
- return client
- def main():
- options = ParseInputs()
- conn = connect(options)
- # print conn
- cursor = conn.cursor()
- try:
- cursor.execute("SELECT COUNT(f_geometry_column) FROM public.geometry_columns")
- except psycopg2.Error, e:
- sys.exit('The database have not PostGIS extension')
- cursor.execute("BEGIN TRANSACTION")
- cursor.execute("CREATE TABLE IF NOT EXISTS import_gdb (id SERIAL NOT NULL PRIMARY KEY, path text, geometry geometry)")
- cursor.execute("END TRANSACTION")
- cursor.execute("CREATE INDEX import_gdb_rtee ON import_gdb USING gist (geometry)")
- for path, subdirs, files in os.walk(options.dir):
- for name in files:
- file = os.path.join(path, name)
- if file.lower().endswith(('.gdb')):
- driver = ogr.GetDriverByName("FileGDB")
- dataSource = driver.Open(file, 0)
- multipolygon = ogr.Geometry(ogr.wkbMultiPolygon)
- for l in range( dataSource.GetLayerCount() ):
- layer = dataSource.GetLayer(l)
- layerDefinition = layer.GetLayerDefn()
- layerName = layer.GetName()
- feat = layer.GetNextFeature()
- geom = feat.GetGeometryRef()
- if geom.GetGeometryName() == 'POLYGON' or geom.GetGeometryName() == 'MULTIPOLYGON':
- for feature in layer:
- multipolygon.AddGeometry(feature.GetGeometryRef())
- cursor.execute("".join(["INSERT INTO import_gdb(path, geometry) VALUES ('", file, "',ST_GeomFromText('", multipolygon.ExportToWkt(),"'))"]))
- cursor.close()
- if conn:
- conn.close()
- return 0
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement