GRASS Programmer's Manual  6.4.2(2012)
 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(table, sql, file = False, **args):
88  """!Perform SQL select statement
89 
90  @param table table name
91  @param sql SQL select statement (string or file)
92  @param file True if sql is filename
93  @param args see db.select arguments
94  """
95  fname = tempfile()
96  if not file:
97  ret = run_command('db.select', quiet = True,
98  flags = 'c',
99  table = table,
100  sql = sql,
101  output = fname,
102  **args)
103  else: # -> sql is file
104  ret = run_command('db.select', quiet = True,
105  flags = 'c',
106  table = table,
107  input = sql,
108  output = fname,
109  **args)
110 
111  if ret != 0:
112  fatal(_("Fetching data from table <%s> failed") % table)
113 
114  ofile = open(fname)
115  result = map(lambda x: x.rstrip(os.linesep), ofile.readlines())
116  ofile.close()
117  try_remove(fname)
118 
119  return result