GRASS Programmer's Manual  6.5.svn(2014)-r66266
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
db.py
Go to the documentation of this file.
1 """!@package grass.script.db
2 
3 @brief GRASS Python scripting module (database functions)
4 
5 Database related functions to be used in Python scripts.
6 
7 Usage:
8 
9 @code
10 from grass.script import db as grass
11 
12 grass.db_describe(table)
13 ...
14 @endcode
15 
16 (C) 2008-2009 by the GRASS Development Team
17 This program is free software under the GNU General Public
18 License (>=v2). Read the file COPYING that comes with GRASS
19 for details.
20 
21 @author Glynn Clements
22 @author Martin Landa <landa.martin gmail.com>
23 """
24 
25 import tempfile as pytempfile # conflict with core.tempfile
26 
27 from core import *
28 
29 # i18N
30 import gettext
31 gettext.install('grasslibs', os.path.join(os.getenv("GISBASE"), 'locale'), unicode=True)
32 
33 def db_describe(table, **args):
34  """!Return the list of columns for a database table
35  (interface to `db.describe -c'). Example:
36 
37  \code
38  >>> grass.db_describe('lakes')
39  {'nrows': 15279, 'cols': [['cat', 'INTEGER', '11'], ['AREA', 'DOUBLE PRECISION', '20'],
40  ['PERIMETER', 'DOUBLE PRECISION', '20'], ['FULL_HYDRO', 'DOUBLE PRECISION', '20'],
41  ['FULL_HYDR2', 'DOUBLE PRECISION', '20'], ['FTYPE', 'CHARACTER', '24'],
42  ['FCODE', 'INTEGER', '11'], ['NAME', 'CHARACTER', '99']], 'ncols': 8}
43  \endcode
44 
45  @param table table name
46  @param args
47 
48  @return parsed module output
49  """
50  s = read_command('db.describe', flags = 'c', table = table, **args)
51  if not s:
52  fatal(_("Unable to describe table <%s>") % table)
53 
54  cols = []
55  result = {}
56  for l in s.splitlines():
57  f = l.split(':')
58  key = f[0]
59  f[1] = f[1].lstrip(' ')
60  if key.startswith('Column '):
61  n = int(key.split(' ')[1])
62  cols.insert(n, f[1:])
63  elif key in ['ncols', 'nrows']:
64  result[key] = int(f[1])
65  else:
66  result[key] = f[1:]
67  result['cols'] = cols
68 
69  return result
70 
71 # run "db.connect -p" and parse output
72 
74  """!Return the current database connection parameters
75  (interface to `db.connect -p'). Example:
76 
77  \code
78  >>> grass.db_connection()
79  {'group': 'x', 'schema': '', 'driver': 'dbf', 'database': '$GISDBASE/$LOCATION_NAME/$MAPSET/dbf/'}
80  \endcode
81 
82  @return parsed output of db.connect
83  """
84  s = read_command('db.connect', flags = 'p')
85  return parse_key_val(s, sep = ':')
86 
87 def db_select(sql = None, filename = None, table = None, **args):
88  """!Perform SQL select statement
89 
90  Note: one of <em>sql</em>, <em>filename</em>, or <em>table</em>
91  arguments must be provided.
92 
93  Examples:
94 
95  \code
96  grass.db_select(sql = 'SELECT cat,CAMPUS FROM busstopsall WHERE cat < 4')
97 
98  (('1', 'Vet School'), ('2', 'West'), ('3', 'North'))
99  \endcode
100 
101  \code
102  grass.db_select(filename = '/path/to/sql/file')
103  \endcode
104 
105  Simplyfied usage
106 
107  \code
108  grass.db_select(table = 'busstopsall')
109  \endcode
110 
111  performs <tt>SELECT * FROM busstopsall</tt>.
112 
113  @param sql SQL statement to perform (or None)
114  @param filename name of file with SQL statements (or None)
115  @param table name of table to query (or None)
116  @param args see db.select arguments
117  """
118  fname = tempfile()
119  if sql:
120  args['sql'] = sql
121  elif filename:
122  args['input'] = filename
123  elif table:
124  args['table'] = table
125  else:
126  fatal(_("Programmer error: '%(sql)s', '%(filename)s', or '%(table)s' must be provided") %
127  {'sql': 'sql', 'filename': 'filename', 'table': 'table'} )
128 
129  if 'fs' not in args:
130  args['fs'] = '|'
131 
132  ret = run_command('db.select', quiet = True,
133  flags = 'c',
134  output = fname,
135  **args)
136 
137  if ret != 0:
138  fatal(_("Fetching data failed"))
139 
140  ofile = open(fname)
141  result = map(lambda x: tuple(x.rstrip(os.linesep).split(args['fs'])),
142  ofile.readlines())
143  ofile.close()
144  try_remove(fname)
145 
146  return tuple(result)
147 
def db_connection
Return the current database connection parameters (interface to `db.connect -p&#39;). ...
Definition: db.py:73
def db_describe
Return the list of columns for a database table (interface to `db.describe -c&#39;).
Definition: db.py:33
def split
Platform spefic shlex.split.
Definition: core/utils.py:37
def fatal
Display an error message using g.message -e, then abort.
Definition: core.py:383
def parse_key_val
Parse a string into a dictionary, where entries are separated by newlines and the key and value are s...
Definition: core.py:505
def try_remove
Attempt to remove a file; no exception is generated if the attempt fails.
Definition: core.py:1010
def db_select
Perform SQL select statement.
Definition: db.py:87
def run_command
Passes all arguments to start_command(), then waits for the process to complete, returning its exit c...
Definition: core.py:179
def read_command
Passes all arguments to pipe_command, then waits for the process to complete, returning its stdout (i...
Definition: core.py:229