2
Database related functions to be used in Python scripts.
8
from grass.script import db as grass
10
grass.db_describe(table)
13
(C) 2008-2009, 2012 by the GRASS Development Team
14
This program is free software under the GNU General Public
15
License (>=v2). Read the file COPYING that comes with GRASS
18
.. sectionauthor:: Glynn Clements
19
.. sectionauthor:: Martin Landa <landa.martin gmail.com>
23
from utils import try_remove
24
from grass.exceptions import CalledModuleError
27
def db_describe(table, **args):
28
"""Return the list of columns for a database table
29
(interface to `db.describe -c`). Example:
31
>>> run_command('g.copy', vector='firestations,myfirestations')
33
>>> db_describe('myfirestations') # doctest: +ELLIPSIS
34
{'nrows': 71, 'cols': [['cat', 'INTEGER', '20'], ... 'ncols': 22}
35
>>> run_command('g.remove', flags='f', type='vector', name='myfirestations')
38
:param str table: table name
41
:return: parsed module output
43
s = read_command('db.describe', flags='c', table=table, **args)
45
fatal(_("Unable to describe table <%s>") % table)
49
for l in s.splitlines():
52
f[1] = f[1].lstrip(' ')
53
if key.startswith('Column '):
54
n = int(key.split(' ')[1])
56
elif key in ['ncols', 'nrows']:
57
result[key] = int(f[1])
65
def db_table_exist(table, **args):
66
"""Check if table exists.
68
If no driver or database are given, then default settings is used
69
(check db_connection()).
71
>>> run_command('g.copy', vector='firestations,myfirestations')
73
>>> db_table_exist('myfirestations')
75
>>> run_command('g.remove', flags='f', type='vector', name='myfirestations')
78
:param str table: table name
81
:return: True for success, False otherwise
83
nuldev = file(os.devnull, 'w+')
86
run_command('db.describe', flags='c', table=table,
87
stdout=nuldev, stderr=nuldev, **args)
88
except CalledModuleError:
96
def db_connection(force=False):
97
"""Return the current database connection parameters
98
(interface to `db.connect -g`). Example:
101
{'group': '', 'schema': '', 'driver': 'sqlite', 'database': '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'}
103
:param force True to set up default DB connection if not defined
105
:return: parsed output of db.connect
107
nuldev = file(os.devnull, 'w')
108
conn = parse_command('db.connect', flags='g', stderr=nuldev)
110
if not conn and force:
111
run_command('db.connect', flags='c')
112
conn = parse_command('db.connect', flags='g')
116
def db_select(sql=None, filename=None, table=None, **args):
117
"""Perform SQL select statement
119
Note: one of <em>sql</em>, <em>filename</em>, or <em>table</em>
120
arguments must be provided.
124
>>> run_command('g.copy', vector='firestations,myfirestations')
126
>>> db_select(sql = 'SELECT cat,CITY FROM myfirestations WHERE cat < 4')
127
(('1', 'Morrisville'), ('2', 'Morrisville'), ('3', 'Apex'))
129
Simplyfied usage (it performs <tt>SELECT * FROM myfirestations</tt>.)
131
>>> db_select(table = 'myfirestations') # doctest: +ELLIPSIS
132
(('1', '24', 'Morrisville #3', ... 'HS2A', '1.37'))
133
>>> run_command('g.remove', flags='f', type='vector', name='myfirestations')
136
:param str sql: SQL statement to perform (or None)
137
:param str filename: name of file with SQL statements (or None)
138
:param str table: name of table to query (or None)
139
:param str args: see \gmod{db.select} arguments
141
fname = tempfile(create=False)
145
args['input'] = filename
147
args['table'] = table
149
fatal(_("Programmer error: '%(sql)s', '%(filename)s', or '%(table)s' must be provided") %
150
{'sql': 'sql', 'filename': 'filename', 'table': 'table'} )
152
if 'sep' not in args:
156
run_command('db.select', quiet=True, flags='c',
157
output=fname, **args)
158
except CalledModuleError:
159
fatal(_("Fetching data failed"))
162
result = map(lambda x: tuple(x.rstrip(os.linesep).split(args['sep'])),
170
def db_table_in_vector(table):
171
"""Return the name of vector connected to the table.
172
It returns None if no vectors are connected to the table.
174
>>> run_command('g.copy', vector='firestations,myfirestations')
176
>>> db_table_in_vector('myfirestations')
177
['myfirestations@user1']
178
>>> db_table_in_vector('mfirestations')
179
>>> run_command('g.remove', flags='f', type='vector', name='myfirestations')
182
:param str table: name of table to query
184
from vector import vector_db
185
nuldev = file(os.devnull, 'w')
187
vects = list_strings('vect')
189
for f in vector_db(vect, stderr=nuldev).itervalues():
192
if f['table'] == table: