table.py 42 KB

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