table.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Wed Aug 8 15:29:21 2012
  4. @author: pietro
  5. """
  6. from __future__ import (nested_scopes, generators, division, absolute_import,
  7. with_statement, print_function, unicode_literals)
  8. import os
  9. import sys
  10. long = int if sys.version_info[0] == 3 else long
  11. import ctypes
  12. import numpy as np
  13. from sqlite3 import OperationalError
  14. try:
  15. from collections import OrderedDict
  16. except:
  17. from grass.pygrass.orderdict import OrderedDict
  18. import grass.lib.vector as libvect
  19. from grass.pygrass.gis import Mapset
  20. from grass.pygrass.errors import DBError
  21. from grass.pygrass.utils import table_exist
  22. from grass.script.db import db_table_in_vector
  23. from grass.script.core import warning
  24. from grass.pygrass.vector import sql
  25. DRIVERS = ('sqlite', 'pg')
  26. def get_path(path):
  27. """Return the full path to the database; replacing environment variable
  28. with real values
  29. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
  30. >>> new_path = get_path(path)
  31. >>> from grass.script.core import gisenv
  32. >>> import os
  33. >>> new_path2 = os.path.join(gisenv()['GISDBASE'], gisenv()['LOCATION_NAME'],
  34. ... gisenv()['MAPSET'], 'sqlite', 'sqlite.db')
  35. >>> new_path == new_path2
  36. True
  37. """
  38. if "$" not in path:
  39. return path
  40. else:
  41. mapset = Mapset()
  42. path = path.replace('$GISDBASE', mapset.gisdbase)
  43. path = path.replace('$LOCATION_NAME', mapset.location)
  44. path = path.replace('$MAPSET', mapset.name)
  45. return path
  46. class Filters(object):
  47. """Help user to build a simple sql query.
  48. >>> filter = Filters('table')
  49. >>> filter.get_sql()
  50. u'SELECT * FROM table;'
  51. >>> filter.where("area<10000").get_sql()
  52. u'SELECT * FROM table WHERE area<10000;'
  53. >>> filter.select("cat", "area").get_sql()
  54. u'SELECT cat, area FROM table WHERE area<10000;'
  55. >>> filter.order_by("area").limit(10).get_sql()
  56. u'SELECT cat, area FROM table WHERE area<10000 ORDER BY area LIMIT 10;'
  57. """
  58. def __init__(self, tname):
  59. self.tname = tname
  60. self._select = None
  61. self._where = None
  62. self._orderby = None
  63. self._limit = None
  64. self._groupby = None
  65. def __repr__(self):
  66. return "Filters(%r)" % self.get_sql()
  67. def select(self, *args):
  68. """Create the select query"""
  69. cols = ', '.join(args) if args else '*'
  70. select = sql.SELECT[:-1]
  71. self._select = select.format(cols=cols, tname=self.tname)
  72. return self
  73. def where(self, condition):
  74. """Create the where condition
  75. :param condition: the condition of where statement, for example
  76. `cat = 1`
  77. :type condition: str
  78. """
  79. self._where = 'WHERE {condition}'.format(condition=condition)
  80. return self
  81. def order_by(self, orderby):
  82. """Create the order by condition
  83. :param orderby: the name of column/s to order the result
  84. :type orderby: str
  85. """
  86. if not isinstance(orderby, unicode):
  87. orderby = ', '.join(orderby)
  88. self._orderby = 'ORDER BY {orderby}'.format(orderby=orderby)
  89. return self
  90. def limit(self, number):
  91. """Create the limit condition
  92. :param number: the number to limit the result
  93. :type number: int
  94. """
  95. if not isinstance(number, int):
  96. raise ValueError("Must be an integer.")
  97. else:
  98. self._limit = 'LIMIT {number}'.format(number=number)
  99. return self
  100. def group_by(self, groupby):
  101. """Create the group by condition
  102. :param groupby: the name of column/s to group the result
  103. :type groupby: str, list
  104. """
  105. if not isinstance(groupby, unicode):
  106. groupby = ', '.join(groupby)
  107. self._groupby = 'GROUP BY {groupby}'.format(groupby=groupby)
  108. return self
  109. def get_sql(self):
  110. """Return the SQL query"""
  111. sql_list = list()
  112. if self._select is None:
  113. self.select()
  114. sql_list.append(self._select)
  115. if self._where is not None:
  116. sql_list.append(self._where)
  117. if self._groupby is not None:
  118. sql_list.append(self._groupby)
  119. if self._orderby is not None:
  120. sql_list.append(self._orderby)
  121. if self._limit is not None:
  122. sql_list.append(self._limit)
  123. return "%s;" % ' '.join(sql_list)
  124. def reset(self):
  125. """Clean internal variables"""
  126. self._select = None
  127. self._where = None
  128. self._orderby = None
  129. self._limit = None
  130. self._groupby = None
  131. class Columns(object):
  132. """Object to work with columns table.
  133. It is possible to instantiate a Columns object given the table name and
  134. the database connection.
  135. For a sqlite table:
  136. >>> import sqlite3
  137. >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
  138. >>> cols_sqlite = Columns('census',
  139. ... sqlite3.connect(get_path(path)))
  140. >>> cols_sqlite.tname
  141. u'census'
  142. For a postgreSQL table:
  143. >>> import psycopg2 as pg #doctest: +SKIP
  144. >>> cols_pg = Columns('boundary_municp_pg',
  145. ... pg.connect('host=localhost dbname=grassdb')) #doctest: +SKIP
  146. >>> cols_pg.tname #doctest: +SKIP
  147. 'boundary_municp_pg' #doctest: +SKIP
  148. """
  149. def __init__(self, tname, connection, key='cat'):
  150. self.tname = tname
  151. self.conn = connection
  152. self.key = key
  153. self.odict = None
  154. self.update_odict()
  155. def __contains__(self, item):
  156. return item in self.names()
  157. def __repr__(self):
  158. return "Columns(%r)" % self.items()
  159. def __getitem__(self, key):
  160. return self.odict[key]
  161. def __setitem__(self, name, new_type):
  162. self.cast(name, new_type)
  163. self.update_odict(self)
  164. def __iter__(self):
  165. return self.odict.__iter__()
  166. def __len__(self):
  167. return self.odict.__len__()
  168. def __eq__(self, obj):
  169. """Return True if two table have the same columns.
  170. >>> import sqlite3
  171. >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
  172. >>> connection = sqlite3.connect(get_path(path))
  173. >>> cols0 = Columns('census', connection)
  174. >>> cols1 = Columns('census', connection)
  175. >>> cols2 = Columns('hospitals', connection)
  176. >>> cols0 == cols1
  177. True
  178. >>> cols1 == cols2
  179. False
  180. """
  181. return obj.tname == self.tname and obj.odict == self.odict
  182. def __ne__(self, other):
  183. return not self == other
  184. # Restore Python 2 hashing beaviour on Python 3
  185. __hash__ = object.__hash__
  186. def is_pg(self):
  187. """Return True if is a psycopg connection.
  188. >>> import sqlite3
  189. >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
  190. >>> cols_sqlite = Columns('census',
  191. ... sqlite3.connect(get_path(path)))
  192. >>> cols_sqlite.is_pg()
  193. False
  194. >>> import psycopg2 as pg #doctest: +SKIP
  195. >>> cols_pg = Columns('boundary_municp_pg',
  196. ... pg.connect('host=localhost dbname=grassdb')) #doctest: +SKIP
  197. >>> cols_pg.is_pg() #doctest: +SKIP
  198. True
  199. """
  200. return hasattr(self.conn, 'xid')
  201. def update_odict(self):
  202. """Read columns name and types from table and update the odict
  203. attribute.
  204. """
  205. if self.is_pg():
  206. # is a postgres connection
  207. cur = self.conn.cursor()
  208. cur.execute("SELECT oid,typname FROM pg_type")
  209. diz = dict(cur.fetchall())
  210. odict = OrderedDict()
  211. import psycopg2 as pg
  212. try:
  213. cur.execute(sql.SELECT.format(cols='*', tname=self.tname))
  214. descr = cur.description
  215. for column in descr:
  216. name, ctype = column[:2]
  217. odict[name] = diz[ctype]
  218. except pg.ProgrammingError:
  219. pass
  220. self.odict = odict
  221. else:
  222. # is a sqlite connection
  223. cur = self.conn.cursor()
  224. cur.execute(sql.PRAGMA.format(tname=self.tname))
  225. descr = cur.fetchall()
  226. odict = OrderedDict()
  227. for column in descr:
  228. name, ctype = column[1:3]
  229. odict[name] = ctype
  230. self.odict = odict
  231. values = ','.join(['?', ] * self.__len__())
  232. kv = ','.join(['%s=?' % k for k in self.odict.keys() if k != self.key])
  233. where = "%s=?" % self.key
  234. self.insert_str = sql.INSERT.format(tname=self.tname, values=values)
  235. self.update_str = sql.UPDATE_WHERE.format(tname=self.tname,
  236. values=kv, condition=where)
  237. def sql_descr(self, remove=None):
  238. """Return a string with description of columns.
  239. Remove it is used to remove a columns.
  240. >>> import sqlite3
  241. >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
  242. >>> cols_sqlite = Columns('census',
  243. ... sqlite3.connect(get_path(path)))
  244. >>> cols_sqlite.sql_descr() # doctest: +ELLIPSIS
  245. u'cat integer, OBJECTID integer, AREA double precision, ...'
  246. >>> import psycopg2 as pg # doctest: +SKIP
  247. >>> cols_pg = Columns('boundary_municp_pg',
  248. ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
  249. >>> cols_pg.sql_descr() # doctest: +ELLIPSIS +SKIP
  250. 'cat int4, objectid int4, area float8, perimeter float8, ...'
  251. """
  252. if remove:
  253. return ', '.join(['%s %s' % (key, val) for key, val in self.items()
  254. if key != remove])
  255. else:
  256. return ', '.join(['%s %s' % (key, val)
  257. for key, val in self.items()])
  258. def types(self):
  259. """Return a list with the column types.
  260. >>> import sqlite3
  261. >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
  262. >>> cols_sqlite = Columns('census',
  263. ... sqlite3.connect(get_path(path)))
  264. >>> cols_sqlite.types() # doctest: +ELLIPSIS
  265. [u'integer', u'integer', ...]
  266. >>> import psycopg2 as pg # doctest: +SKIP
  267. >>> cols_pg = Columns('boundary_municp_pg',
  268. ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
  269. >>> cols_pg.types() # doctest: +ELLIPSIS +SKIP
  270. ['int4', 'int4', 'float8', 'float8', 'float8', ...]
  271. """
  272. return self.odict.values()
  273. def names(self, remove=None, unicod=True):
  274. """Return a list with the column names.
  275. Remove it is used to remove a columns.
  276. >>> import sqlite3
  277. >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
  278. >>> cols_sqlite = Columns('census',
  279. ... sqlite3.connect(get_path(path)))
  280. >>> cols_sqlite.names() # doctest: +ELLIPSIS
  281. [u'cat', u'OBJECTID', u'AREA', u'PERIMETER', ...]
  282. >>> import psycopg2 as pg # doctest: +SKIP
  283. >>> cols_pg = Columns('boundary_municp_pg', # doctest: +SKIP
  284. ... pg.connect('host=localhost dbname=grassdb'))
  285. >>> cols_pg.names() # doctest: +ELLIPSIS +SKIP
  286. ['cat', 'objectid', 'area', 'perimeter', ...]
  287. """
  288. if remove:
  289. nams = self.odict.keys()
  290. nams.remove(remove)
  291. else:
  292. nams = self.odict.keys()
  293. if unicod:
  294. return nams
  295. else:
  296. return [str(name) for name in nams]
  297. def items(self):
  298. """Return a list of tuple with column name and column type.
  299. >>> import sqlite3
  300. >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
  301. >>> cols_sqlite = Columns('census',
  302. ... sqlite3.connect(get_path(path)))
  303. >>> cols_sqlite.items() # doctest: +ELLIPSIS
  304. [(u'cat', u'integer'), ...]
  305. >>> import psycopg2 as pg # doctest: +SKIP
  306. >>> cols_pg = Columns('boundary_municp_pg',
  307. ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
  308. >>> cols_pg.items() # doctest: +ELLIPSIS +SKIP
  309. [('cat', 'int4'), ('objectid', 'int4'), ('area', 'float8'), ...]
  310. """
  311. return self.odict.items()
  312. def add(self, col_name, col_type):
  313. """Add a new column to the table.
  314. :param col_name: the name of column to add
  315. :type col_name: str
  316. :param col_type: the tipe of column to add
  317. :type col_type: str
  318. >>> import sqlite3
  319. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
  320. >>> from grass.pygrass.utils import copy, remove
  321. >>> copy('census','mycensus','vect')
  322. >>> cols_sqlite = Columns('mycensus',
  323. ... sqlite3.connect(get_path(path)))
  324. >>> cols_sqlite.add(['n_pizza'], ['INT'])
  325. >>> 'n_pizza' in cols_sqlite
  326. True
  327. >>> import psycopg2 as pg # doctest: +SKIP
  328. >>> cols_pg = Columns('boundary_municp_pg',
  329. ... pg.connect('host=localhost dbname=grassdb')) #doctest: +SKIP
  330. >>> cols_pg.add('n_pizza', 'INT') # doctest: +SKIP
  331. >>> 'n_pizza' in cols_pg # doctest: +SKIP
  332. True
  333. >>> remove('mycensus', 'vect')
  334. """
  335. def check(col_type):
  336. """Check the column type if it is supported by GRASS
  337. :param col_type: the type of column
  338. :type col_type: str
  339. """
  340. valid_type = ('DOUBLE PRECISION', 'DOUBLE', 'INT', 'INTEGER',
  341. 'DATE')
  342. if 'VARCHAR' in col_type or col_type.upper() not in valid_type:
  343. str_err = "Type is not supported, supported types are: %s"
  344. raise TypeError(str_err % ", ".join(valid_type))
  345. return col_type
  346. col_type = ([check(col_type), ] if isinstance(col_type, (str, unicode))
  347. else [check(col) for col in col_type])
  348. col_name = ([col_name, ] if isinstance(col_name, (str, unicode))
  349. else col_name)
  350. sqlcode = [sql.ADD_COL.format(tname=self.tname, cname=cn, ctype=ct)
  351. for cn, ct in zip(col_name, col_type)]
  352. cur = self.conn.cursor()
  353. cur.executescript('\n'.join(sqlcode))
  354. self.conn.commit()
  355. cur.close()
  356. self.update_odict()
  357. def rename(self, old_name, new_name):
  358. """Rename a column of the table.
  359. :param old_name: the name of existing column
  360. :type old_name: str
  361. :param new_name: the name of new column
  362. :type new_name: str
  363. >>> import sqlite3
  364. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
  365. >>> from grass.pygrass.utils import copy, remove
  366. >>> copy('census','mycensus','vect')
  367. >>> cols_sqlite = Columns('mycensus',
  368. ... sqlite3.connect(get_path(path)))
  369. >>> cols_sqlite.add(['n_pizza'], ['INT'])
  370. >>> 'n_pizza' in cols_sqlite
  371. True
  372. >>> cols_sqlite.rename('n_pizza', 'n_pizzas') # doctest: +ELLIPSIS
  373. >>> 'n_pizza' in cols_sqlite
  374. False
  375. >>> 'n_pizzas' in cols_sqlite
  376. True
  377. >>> import psycopg2 as pg # doctest: +SKIP
  378. >>> cols_pg = Columns('boundary_municp_pg',
  379. ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
  380. >>> cols_pg.rename('n_pizza', 'n_pizzas') # doctest: +SKIP
  381. >>> 'n_pizza' in cols_pg # doctest: +SKIP
  382. False
  383. >>> 'n_pizzas' in cols_pg # doctest: +SKIP
  384. True
  385. >>> remove('mycensus', 'vect')
  386. """
  387. cur = self.conn.cursor()
  388. if self.is_pg():
  389. cur.execute(sql.RENAME_COL.format(tname=self.tname,
  390. old_name=old_name,
  391. new_name=new_name))
  392. self.conn.commit()
  393. cur.close()
  394. self.update_odict()
  395. else:
  396. cur.execute(sql.ADD_COL.format(tname=self.tname,
  397. cname=new_name,
  398. ctype=str(self.odict[old_name])))
  399. cur.execute(sql.UPDATE.format(tname=self.tname,
  400. new_col=new_name,
  401. old_col=old_name))
  402. self.conn.commit()
  403. cur.close()
  404. self.update_odict()
  405. self.drop(old_name)
  406. def cast(self, col_name, new_type):
  407. """Change the column type.
  408. :param col_name: the name of column
  409. :type col_name: str
  410. :param new_type: the new type of column
  411. :type new_type: str
  412. >>> import sqlite3
  413. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
  414. >>> from grass.pygrass.utils import copy, remove
  415. >>> copy('census','mycensus','vect')
  416. >>> cols_sqlite = Columns('mycensus',
  417. ... sqlite3.connect(get_path(path)))
  418. >>> cols_sqlite.add(['n_pizzas'], ['INT'])
  419. >>> cols_sqlite.cast('n_pizzas', 'float8') # doctest: +ELLIPSIS
  420. Traceback (most recent call last):
  421. ...
  422. DBError: SQLite does not support to cast columns.
  423. >>> import psycopg2 as pg # doctest: +SKIP
  424. >>> cols_pg = Columns('boundary_municp_pg',
  425. ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
  426. >>> cols_pg.cast('n_pizzas', 'float8') # doctest: +SKIP
  427. >>> cols_pg['n_pizzas'] # doctest: +SKIP
  428. 'float8'
  429. >>> remove('mycensus', 'vect')
  430. .. warning ::
  431. It is not possible to cast a column with sqlite
  432. """
  433. if self.is_pg():
  434. cur = self.conn.cursor()
  435. cur.execute(sql.CAST_COL.format(tname=self.tname, col=col_name,
  436. ctype=new_type))
  437. self.conn.commit()
  438. cur.close()
  439. self.update_odict()
  440. else:
  441. # sqlite does not support rename columns:
  442. raise DBError('SQLite does not support to cast columns.')
  443. def drop(self, col_name):
  444. """Drop a column from the table.
  445. :param col_name: the name of column to remove
  446. :type col_name: str
  447. >>> import sqlite3
  448. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
  449. >>> from grass.pygrass.utils import copy, remove
  450. >>> copy('census','mycensus','vect')
  451. >>> cols_sqlite = Columns('mycensus',
  452. ... sqlite3.connect(get_path(path)))
  453. >>> cols_sqlite.drop('CHILD') # doctest: +ELLIPSIS
  454. >>> 'CHILD' in cols_sqlite
  455. False
  456. >>> import psycopg2 as pg # doctest: +SKIP
  457. >>> cols_pg = Columns('boundary_municp_pg',
  458. ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
  459. >>> cols_pg.drop('CHILD') # doctest: +SKIP
  460. >>> 'CHILD' in cols_pg # doctest: +SKIP
  461. False
  462. >>> remove('mycensus','vect')
  463. """
  464. cur = self.conn.cursor()
  465. if self.is_pg():
  466. cur.execute(sql.DROP_COL.format(tname=self.tname,
  467. cname=col_name))
  468. else:
  469. desc = str(self.sql_descr(remove=col_name))
  470. names = ', '.join(self.names(remove=col_name, unicod=False))
  471. queries = sql.DROP_COL_SQLITE.format(tname=self.tname,
  472. keycol=self.key,
  473. coldef=desc,
  474. colnames=names).split('\n')
  475. for query in queries:
  476. cur.execute(query)
  477. self.conn.commit()
  478. cur.close()
  479. self.update_odict()
  480. class Link(object):
  481. """Define a Link between vector map and the attributes table.
  482. It is possible to define a Link object or given all the information
  483. (layer, name, table name, key, database, driver):
  484. >>> link = Link(1, 'link0', 'census', 'cat',
  485. ... '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db', 'sqlite')
  486. >>> link.layer
  487. 1
  488. >>> link.name
  489. 'link0'
  490. >>> link.table_name
  491. 'census'
  492. >>> link.key
  493. 'cat'
  494. >>> link.database
  495. '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
  496. >>> link.driver
  497. 'sqlite'
  498. >>> link
  499. Link(1, link0, sqlite)
  500. It is possible to change parameters with:
  501. >>> link.driver = 'pg' # doctest: +SKIP
  502. >>> link.driver # doctest: +SKIP
  503. 'pg'
  504. >>> link.driver = 'postgres' # doctest: +ELLIPSIS +SKIP
  505. Traceback (most recent call last):
  506. ...
  507. TypeError: Driver not supported, use: sqlite, pg.
  508. >>> link.driver # doctest: +SKIP
  509. 'pg'
  510. >>> link.number = 0 # doctest: +ELLIPSIS +SKIP
  511. Traceback (most recent call last):
  512. ...
  513. TypeError: Number must be positive and greater than 0.
  514. Or given a c_fieldinfo object that is a ctypes pointer to the field_info C
  515. struct. ::
  516. >>> link = Link(c_fieldinfo = ctypes.pointer(libvect.field_info()))
  517. """
  518. def _get_layer(self):
  519. return self.c_fieldinfo.contents.number
  520. def _set_layer(self, number):
  521. if number <= 0:
  522. raise TypeError("Number must be positive and greater than 0.")
  523. self.c_fieldinfo.contents.number = number
  524. layer = property(fget=_get_layer, fset=_set_layer,
  525. doc="Set and obtain layer number")
  526. def _get_name(self):
  527. return self.c_fieldinfo.contents.name
  528. def _set_name(self, name):
  529. self.c_fieldinfo.contents.name = name
  530. name = property(fget=_get_name, fset=_set_name,
  531. doc="Set and obtain name vale")
  532. def _get_table(self):
  533. return self.c_fieldinfo.contents.table
  534. def _set_table(self, new_name):
  535. self.c_fieldinfo.contents.table = new_name
  536. table_name = property(fget=_get_table, fset=_set_table,
  537. doc="Set and obtain table name value")
  538. def _get_key(self):
  539. return self.c_fieldinfo.contents.key
  540. def _set_key(self, key):
  541. self.c_fieldinfo.contents.key = key
  542. key = property(fget=_get_key, fset=_set_key,
  543. doc="Set and obtain cat value")
  544. def _get_database(self):
  545. return self.c_fieldinfo.contents.database
  546. def _set_database(self, database):
  547. self.c_fieldinfo.contents.database = database
  548. database = property(fget=_get_database, fset=_set_database,
  549. doc="Set and obtain database value")
  550. def _get_driver(self):
  551. return self.c_fieldinfo.contents.driver
  552. def _set_driver(self, driver):
  553. if driver not in ('sqlite', 'pg'):
  554. str_err = "Driver not supported, use: %s." % ", ".join(DRIVERS)
  555. raise TypeError(str_err)
  556. self.c_fieldinfo.contents.driver = driver
  557. driver = property(fget=_get_driver, fset=_set_driver,
  558. doc="Set and obtain driver value. The drivers supported \
  559. by PyGRASS are: SQLite and PostgreSQL")
  560. def __init__(self, layer=1, name=None, table=None, key='cat',
  561. database='$GISDBASE/$LOCATION_NAME/'
  562. '$MAPSET/sqlite/sqlite.db',
  563. driver='sqlite', c_fieldinfo=None):
  564. if c_fieldinfo is not None:
  565. self.c_fieldinfo = c_fieldinfo
  566. else:
  567. self.c_fieldinfo = ctypes.pointer(libvect.field_info())
  568. self.layer = layer
  569. self.name = name
  570. self.table_name = table
  571. self.key = key
  572. self.database = database
  573. self.driver = driver
  574. def __repr__(self):
  575. return "Link(%d, %s, %s)" % (self.layer, self.name, self.driver)
  576. def __eq__(self, link):
  577. """Return True if two Link instance have the same parameters.
  578. >>> l0 = Link(1, 'link0', 'census', 'cat',
  579. ... '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db', 'sqlite')
  580. >>> l1 = Link(1, 'link0', 'census', 'cat',
  581. ... '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db', 'sqlite')
  582. >>> l2 = Link(2, 'link0', 'census', 'cat',
  583. ... '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db', 'sqlite')
  584. >>> l0 == l1
  585. True
  586. >>> l1 == l2
  587. False
  588. """
  589. attrs = ['layer', 'name', 'table_name', 'key', 'driver']
  590. for attr in attrs:
  591. if getattr(self, attr) != getattr(link, attr):
  592. return False
  593. return True
  594. def __ne__(self, other):
  595. return not self == other
  596. # Restore Python 2 hashing beaviour on Python 3
  597. __hash__ = object.__hash__
  598. def connection(self):
  599. """Return a connection object.
  600. >>> link = Link(1, 'link0', 'census', 'cat',
  601. ... '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db',
  602. ... 'sqlite')
  603. >>> conn = link.connection()
  604. >>> cur = conn.cursor()
  605. >>> cur.execute("SELECT cat,TOTAL_POP,PERIMETER FROM %s" %
  606. ... link.table_name) # doctest: +ELLIPSIS
  607. <sqlite3.Cursor object at ...>
  608. >>> cur.fetchone()
  609. (1, 44, 757.669)
  610. >>> cur.close()
  611. >>> conn.close()
  612. """
  613. if self.driver == 'sqlite':
  614. import sqlite3
  615. # Numpy is using some custom integer data types to efficiently
  616. # pack data into memory. Since these types aren't familiar to
  617. # sqlite, you'll have to tell it about how to handle them.
  618. for t in (np.int8, np.int16, np.int32, np.int64, np.uint8,
  619. np.uint16, np.uint32, np.uint64):
  620. sqlite3.register_adapter(t, long)
  621. dbpath = get_path(self.database)
  622. dbdirpath = os.path.split(dbpath)[0]
  623. if not os.path.exists(dbdirpath):
  624. os.mkdir(dbdirpath)
  625. return sqlite3.connect(dbpath)
  626. elif self.driver == 'pg':
  627. try:
  628. import psycopg2
  629. psycopg2.paramstyle = 'qmark'
  630. db = ' '.join(self.database.split(','))
  631. return psycopg2.connect(db)
  632. except ImportError:
  633. er = "You need to install psycopg2 to connect with this table."
  634. raise ImportError(er)
  635. else:
  636. str_err = "Driver is not supported yet, pleas use: sqlite or pg"
  637. raise TypeError(str_err)
  638. def table(self):
  639. """Return a Table object.
  640. >>> link = Link(1, 'link0', 'census', 'cat',
  641. ... '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db',
  642. ... 'sqlite')
  643. >>> table = link.table()
  644. >>> table.filters.select('cat', 'TOTAL_POP', 'PERIMETER')
  645. Filters(u'SELECT cat, TOTAL_POP, PERIMETER FROM census;')
  646. >>> cur = table.execute()
  647. >>> cur.fetchone()
  648. (1, 44, 757.669)
  649. >>> cur.close()
  650. """
  651. return Table(self.table_name, self.connection(), self.key)
  652. def info(self):
  653. """Print information of the link.
  654. >>> link = Link(1, 'link0', 'census', 'cat',
  655. ... '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db',
  656. ... 'sqlite')
  657. >>> link.info()
  658. layer: 1
  659. name: link0
  660. table: census
  661. key: cat
  662. database: $GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db
  663. driver: sqlite
  664. """
  665. print("layer: ", self.layer)
  666. print("name: ", self.name)
  667. print("table: ", self.table_name)
  668. print("key: ", self.key)
  669. print("database: ", self.database)
  670. print("driver: ", self.driver)
  671. class DBlinks(object):
  672. """Interface containing link to the table DB.
  673. >>> from grass.pygrass.vector import VectorTopo
  674. >>> cens = VectorTopo('census')
  675. >>> cens.open(mode='r')
  676. >>> dblinks = DBlinks(cens.c_mapinfo)
  677. >>> dblinks
  678. DBlinks([Link(1, census, sqlite)])
  679. >>> dblinks[0]
  680. Link(1, census, sqlite)
  681. >>> dblinks['census']
  682. Link(1, census, sqlite)
  683. >>> cens.close()
  684. """
  685. def __init__(self, c_mapinfo):
  686. self.c_mapinfo = c_mapinfo
  687. def __len__(self):
  688. return self.num_dblinks()
  689. def __iter__(self):
  690. return (self.by_index(i)
  691. for i in range(self.num_dblinks()))
  692. def __getitem__(self, item):
  693. """
  694. """
  695. if isinstance(item, int):
  696. return self.by_index(item)
  697. else:
  698. return self.by_name(item)
  699. def __repr__(self):
  700. return "DBlinks(%r)" % [link for link in self.__iter__()]
  701. def by_index(self, indx):
  702. """Return a Link object by index
  703. :param indx: the index where add new point
  704. :type indx: int
  705. """
  706. nlinks = self.num_dblinks()
  707. if nlinks == 0:
  708. raise IndexError
  709. if indx < 0:
  710. indx += nlinks
  711. if indx > nlinks:
  712. raise IndexError
  713. c_fieldinfo = libvect.Vect_get_dblink(self.c_mapinfo, indx)
  714. return Link(c_fieldinfo=c_fieldinfo) if c_fieldinfo else None
  715. def by_layer(self, layer):
  716. """Return the choosen Link using the layer
  717. :param layer: the number of layer
  718. :type layer: int
  719. """
  720. c_fieldinfo = libvect.Vect_get_field(self.c_mapinfo, layer)
  721. return Link(c_fieldinfo=c_fieldinfo) if c_fieldinfo else None
  722. def by_name(self, name):
  723. """Return the choosen Link using the name
  724. :param name: the name of Link
  725. :type name: str
  726. """
  727. c_fieldinfo = libvect.Vect_get_field_by_name(self.c_mapinfo, name)
  728. return Link(c_fieldinfo=c_fieldinfo) if c_fieldinfo else None
  729. def num_dblinks(self):
  730. """Return the number of DBlinks"""
  731. return libvect.Vect_get_num_dblinks(self.c_mapinfo)
  732. def add(self, link):
  733. """Add a new link. Need to open vector map in write mode
  734. :param link: the Link to add to the DBlinks
  735. :type link: a Link object
  736. >>> from grass.pygrass.vector import VectorTopo
  737. >>> municip = VectorTopo('census')
  738. >>> municip.open(mode='r')
  739. >>> dblinks = DBlinks(municip.c_mapinfo)
  740. >>> dblinks
  741. DBlinks([Link(1, census, sqlite)])
  742. >>> link = Link(2, 'pg_link', 'boundary_municp_pg', 'cat',
  743. ... 'host=localhost dbname=grassdb', 'pg') # doctest: +SKIP
  744. >>> dblinks.add(link) # doctest: +SKIP
  745. >>> dblinks # doctest: +SKIP
  746. DBlinks([Link(1, boundary_municp, sqlite)])
  747. """
  748. #TODO: check if open in write mode or not.
  749. libvect.Vect_map_add_dblink(self.c_mapinfo,
  750. link.layer, link.name, link.table_name,
  751. link.key, link.database, link.driver)
  752. def remove(self, key, force=False):
  753. """Remove a link. If force set to true remove also the table
  754. :param key: the key of Link
  755. :type key: str
  756. :param force: if True remove also the table from database otherwise
  757. only the link between table and vector
  758. :type force: boole
  759. >>> from grass.pygrass.vector import VectorTopo
  760. >>> municip = VectorTopo('census')
  761. >>> municip.open(mode='r')
  762. >>> dblinks = DBlinks(municip.c_mapinfo)
  763. >>> dblinks
  764. DBlinks([Link(1, census, sqlite)])
  765. >>> dblinks.remove('pg_link') # doctest: +SKIP
  766. >>> dblinks # need to open vector map in write mode
  767. DBlinks([Link(1, census, sqlite)])
  768. """
  769. if force:
  770. link = self.by_name(key)
  771. table = link.table()
  772. table.drop(force=force)
  773. if isinstance(key, unicode):
  774. key = self.from_name_to_num(key)
  775. libvect.Vect_map_del_dblink(self.c_mapinfo, key)
  776. def from_name_to_num(self, name):
  777. """
  778. Vect_get_field_number
  779. """
  780. return libvect.Vect_get_field_number(self.c_mapinfo, name)
  781. class Table(object):
  782. """
  783. >>> import sqlite3
  784. >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
  785. >>> tab_sqlite = Table(name='census',
  786. ... connection=sqlite3.connect(get_path(path)))
  787. >>> tab_sqlite.name
  788. u'census'
  789. >>> import psycopg2 # doctest: +SKIP
  790. >>> tab_pg = Table('boundary_municp_pg',
  791. ... psycopg2.connect('host=localhost dbname=grassdb',
  792. ... 'pg')) # doctest: +SKIP
  793. >>> tab_pg.columns # doctest: +ELLIPSIS +SKIP
  794. Columns([('cat', 'int4'), ...])
  795. """
  796. def _get_name(self):
  797. """Private method to return the name of table"""
  798. return self._name
  799. def _set_name(self, new_name):
  800. """Private method to set the name of table
  801. :param new_name: the new name of table
  802. :type new_name: str
  803. """
  804. old_name = self._name
  805. cur = self.conn.cursor()
  806. cur.execute(sql.RENAME_TAB.format(old_name=old_name,
  807. new_name=new_name))
  808. self.conn.commit()
  809. cur.close()
  810. name = property(fget=_get_name, fset=_set_name,
  811. doc="Set and obtain table name")
  812. def __init__(self, name, connection, key='cat'):
  813. self._name = name
  814. self.conn = connection
  815. self.key = key
  816. self.columns = Columns(self.name,
  817. self.conn,
  818. self.key)
  819. self.filters = Filters(self.name)
  820. def __repr__(self):
  821. """
  822. >>> import sqlite3
  823. >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
  824. >>> tab_sqlite = Table(name='census',
  825. ... connection=sqlite3.connect(get_path(path)))
  826. >>> tab_sqlite
  827. Table(u'census')
  828. """
  829. return "Table(%r)" % (self.name)
  830. def __iter__(self):
  831. cur = self.execute()
  832. return (cur.fetchone() for _ in range(self.__len__()))
  833. def __len__(self):
  834. """Return the number of rows"""
  835. return self.n_rows()
  836. def drop(self, cursor=None, force=False):
  837. """Method to drop table from database
  838. :param cursor: the cursor to connect, if None it use the cursor
  839. of connection table object
  840. :type cursor: Cursor object
  841. :param force: True to remove the table, by default False to print
  842. advice
  843. :type force: bool
  844. """
  845. cur = cursor if cursor else self.conn.cursor()
  846. if self.exist(cursor=cur):
  847. used = db_table_in_vector(self.name)
  848. if used is not None and len(used) > 0 and not force:
  849. print(_("Deleting table <%s> which is attached"
  850. " to following map(s):") % self.name)
  851. for vect in used:
  852. warning("%s" % vect)
  853. print(_("You must use the force flag to actually"
  854. " remove it. Exiting."))
  855. else:
  856. cur.execute(sql.DROP_TAB.format(tname=self.name))
  857. def n_rows(self):
  858. """Return the number of rows
  859. >>> import sqlite3
  860. >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
  861. >>> tab_sqlite = Table(name='census',
  862. ... connection=sqlite3.connect(get_path(path)))
  863. >>> tab_sqlite.n_rows()
  864. 2537
  865. """
  866. cur = self.conn.cursor()
  867. cur.execute(sql.SELECT.format(cols='Count(*)', tname=self.name))
  868. number = cur.fetchone()[0]
  869. cur.close()
  870. return number
  871. def execute(self, sql_code=None, cursor=None, many=False, values=None):
  872. """Execute SQL code from a given string or build with filters and
  873. return a cursor object.
  874. :param sql_code: the SQL code to execute, if not pass it use filters
  875. variable
  876. :type sql_code: str
  877. :param cursor: the cursor to connect, if None it use the cursor
  878. of connection table object
  879. :type cursor: Cursor object
  880. :param many: True to run executemany function
  881. :type many: bool
  882. :param values: The values to substitute into sql_code string
  883. :type values: list of tuple
  884. >>> import sqlite3
  885. >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
  886. >>> tab_sqlite = Table(name='census',
  887. ... connection=sqlite3.connect(get_path(path)))
  888. >>> tab_sqlite.filters.select('cat', 'TOTAL_POP').order_by('AREA')
  889. Filters(u'SELECT cat, TOTAL_POP FROM census ORDER BY AREA;')
  890. >>> cur = tab_sqlite.execute()
  891. >>> cur.fetchone()
  892. (1856, 0)
  893. """
  894. try:
  895. sqlc = sql_code if sql_code else self.filters.get_sql()
  896. cur = cursor if cursor else self.conn.cursor()
  897. if many and values:
  898. return cur.executemany(sqlc, values)
  899. return cur.execute(sqlc)
  900. except:
  901. #import ipdb; ipdb.set_trace()
  902. raise ValueError("The SQL is not correct:\n%r" % sqlc)
  903. def exist(self, cursor=None):
  904. """Return True if the table already exist in the DB, False otherwise
  905. :param cursor: the cursor to connect, if None it use the cursor
  906. of connection table object
  907. """
  908. cur = cursor if cursor else self.conn.cursor()
  909. return table_exist(cur, self.name)
  910. def insert(self, values, cursor=None, many=False):
  911. """Insert a new row
  912. :param values: a tuple of values to insert, it is possible to insert
  913. more rows using a list of tuple and paramater `many`
  914. :type values: tuple
  915. :param cursor: the cursor to connect, if None it use the cursor
  916. of connection table object
  917. :type cursor: Cursor object
  918. :param many: True to run executemany function
  919. :type many: bool
  920. """
  921. cur = cursor if cursor else self.conn.cursor()
  922. if many:
  923. return cur.executemany(self.columns.insert_str, values)
  924. return cur.execute(self.columns.insert_str, values)
  925. def update(self, key, values, cursor=None):
  926. """Update a table row
  927. :param key: the rowid
  928. :type key: int
  929. :param values: the values to insert without row id.
  930. For example if we have a table with four columns:
  931. cat, c0, c1, c2 the values list should
  932. containing only c0, c1, c2 values.
  933. :type values: list
  934. :param cursor: the cursor to connect, if None it use the cursor
  935. of connection table object
  936. :type cursor: Cursor object
  937. """
  938. cur = cursor if cursor else self.conn.cursor()
  939. vals = list(values) + [key, ]
  940. return cur.execute(self.columns.update_str, vals)
  941. def create(self, cols, name=None, overwrite=False, cursor=None):
  942. """Create a new table
  943. :param cols:
  944. :type cols:
  945. :param name: the name of table to create, None for the name of Table object
  946. :type name: str
  947. :param overwrite: overwrite existing table
  948. :type overwrite: bool
  949. :param cursor: the cursor to connect, if None it use the cursor
  950. of connection table object
  951. :type cursor: Cursor object
  952. """
  953. cur = cursor if cursor else self.conn.cursor()
  954. coldef = ',\n'.join(['%s %s' % col for col in cols])
  955. if name:
  956. newname = name
  957. else:
  958. newname = self.name
  959. try:
  960. cur.execute(sql.CREATE_TAB.format(tname=newname, coldef=coldef))
  961. self.conn.commit()
  962. except OperationalError: # OperationalError
  963. if overwrite:
  964. self.drop(force=True)
  965. cur.execute(sql.CREATE_TAB.format(tname=newname,
  966. coldef=coldef))
  967. self.conn.commit()
  968. else:
  969. print("The table: %s already exist." % self.name)
  970. cur.close()
  971. self.columns.update_odict()