3
############################################################################
5
# MODULE: qgis.db.connect-login.py
6
# AUTHOR(S): Radim Blazek
8
# PURPOSE: Connect to Postgresql
9
# COPYRIGHT: (C) 2009 by Radim Blazek
11
# This program is free software under the GNU General Public
12
# License (>=v2). Read the file COPYING that comes with GRASS
15
#############################################################################
18
#% description: Make connection to PostgreSQL database and login.
26
#% description: Host name of the machine on which the server is running.
34
#% description: TCP port on which the server is listening, usually 5432.
42
#% gisprompt: old_dbname,dbname,dbname
44
#% description: Database name
52
#% description: Database schema.
60
#% description: Connect to the database as the user username instead of the default.
68
#% description: Password will be stored in file!
76
from grass.script import core as grass
80
raise Exception ("Cannot find 'grass' Python module. Python is supported by GRASS from version >= 6.4" )
83
host = options['host']
84
port = options['port']
85
database = options['database']
86
schema = options['schema']
87
user = options['user']
88
password = options['password']
91
conn = "dbname=" + database
92
if host: conn += ",host=" + host
93
if port: conn += ",port=" + port
95
# Unfortunately we cannot test untill user/password is set
97
print "Setting login (db.login) ... "
99
if grass.run_command('db.login', driver = "pg", database = conn, user = user, password = password) != 0:
100
grass.fatal("Cannot login")
103
print "Testing connection ..."
105
if grass.run_command('db.select', quiet = True, flags='c', driver= "pg", database=conn, sql="select version()" ) != 0:
107
print "Deleting login (db.login) ..."
109
if grass.run_command('db.login', quiet = True, driver = "pg", database = conn, user = "", password = "") != 0:
110
print "Cannot delete login."
112
grass.fatal("Cannot connect to database.")
114
if grass.run_command('db.connect', driver = "pg", database = conn, schema = schema) != 0:
115
grass.fatal("Cannot connect to database.")
117
if __name__ == "__main__":
118
options, flags = grass.parser()