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. import sys
  10. if sys.version_info.major == 3:
  11. long = int
  12. unicode = str
  13. import ctypes
  14. import numpy as np
  15. from sqlite3 import OperationalError
  16. try:
  17. from collections import OrderedDict
  18. except:
  19. from grass.pygrass.orderdict import OrderedDict
  20. import grass.lib.vector as libvect
  21. from grass.pygrass.gis import Mapset
  22. from grass.pygrass.errors import DBError
  23. from grass.pygrass.utils import table_exist, decode
  24. from grass.script.db import db_table_in_vector
  25. from grass.script.core import warning
  26. from grass.pygrass.vector import sql
  27. from grass.lib.ctypes_preamble import String
  28. # For test purposes
  29. test_vector_name = "table_doctest_map"
  30. DRIVERS = ('sqlite', 'pg')
  31. def get_path(path, vect_name=None):
  32. """Return the full path to the database; replacing environment variable
  33. with real values
  34. :param path: The path with substitutional parameter
  35. :param vect_name: The name of the vector map
  36. >>> from grass.script.core import gisenv
  37. >>> import os
  38. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
  39. >>> new_path = get_path(path)
  40. >>> new_path2 = os.path.join(gisenv()['GISDBASE'], gisenv()['LOCATION_NAME'],
  41. ... gisenv()['MAPSET'], 'sqlite', 'sqlite.db')
  42. >>> new_path.replace("//","/") == new_path2.replace("//","/")
  43. True
  44. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/vector/$MAP/sqlite.db'
  45. >>> new_path = get_path(path, "test")
  46. >>> new_path2 = os.path.join(gisenv()['GISDBASE'], gisenv()['LOCATION_NAME'],
  47. ... gisenv()['MAPSET'], 'vector', 'test', 'sqlite.db')
  48. >>> new_path.replace("//","/") == new_path2.replace("//","/")
  49. True
  50. """
  51. if "$" not in path:
  52. return path
  53. else:
  54. mapset = Mapset()
  55. path = path.replace('$GISDBASE', mapset.gisdbase)
  56. path = path.replace('$LOCATION_NAME', mapset.location)
  57. path = path.replace('$MAPSET', mapset.name)
  58. if vect_name is not None:
  59. path = path.replace('$MAP', vect_name)
  60. return path
  61. class Filters(object):
  62. """Help user to build a simple sql query.
  63. >>> filter = Filters('table')
  64. >>> filter.get_sql()
  65. 'SELECT * FROM table;'
  66. >>> filter.where("area<10000").get_sql()
  67. 'SELECT * FROM table WHERE area<10000;'
  68. >>> filter.select("cat", "area").get_sql()
  69. 'SELECT cat, area FROM table WHERE area<10000;'
  70. >>> filter.order_by("area").limit(10).get_sql()
  71. 'SELECT cat, area FROM table WHERE area<10000 ORDER BY area LIMIT 10;'
  72. """
  73. def __init__(self, tname):
  74. self.tname = tname
  75. self._select = None
  76. self._where = None
  77. self._orderby = None
  78. self._limit = None
  79. self._groupby = None
  80. def __repr__(self):
  81. return "Filters(%r)" % self.get_sql()
  82. def select(self, *args):
  83. """Create the select query"""
  84. cols = ', '.join(args) if args else '*'
  85. select = sql.SELECT[:-1]
  86. self._select = select.format(cols=cols, tname=self.tname)
  87. return self
  88. def where(self, condition):
  89. """Create the where condition
  90. :param condition: the condition of where statement, for example
  91. `cat = 1`
  92. :type condition: str
  93. """
  94. self._where = 'WHERE {condition}'.format(condition=condition)
  95. return self
  96. def order_by(self, *orderby):
  97. """Create the order by condition
  98. :param orderby: the name of column/s to order the result
  99. :type orderby: str
  100. """
  101. self._orderby = 'ORDER BY {orderby}'.format(orderby=', '.join(orderby))
  102. return self
  103. def limit(self, number):
  104. """Create the limit condition
  105. :param number: the number to limit the result
  106. :type number: int
  107. """
  108. if not isinstance(number, int):
  109. raise ValueError("Must be an integer.")
  110. else:
  111. self._limit = 'LIMIT {number}'.format(number=number)
  112. return self
  113. def group_by(self, *groupby):
  114. """Create the group by condition
  115. :param groupby: the name of column/s to group the result
  116. :type groupby: str, list
  117. """
  118. self._groupby = 'GROUP BY {groupby}'.format(groupby=', '.join(groupby))
  119. return self
  120. def get_sql(self):
  121. """Return the SQL query"""
  122. sql_list = list()
  123. if self._select is None:
  124. self.select()
  125. sql_list.append(self._select)
  126. if self._where is not None:
  127. sql_list.append(self._where)
  128. if self._groupby is not None:
  129. sql_list.append(self._groupby)
  130. if self._orderby is not None:
  131. sql_list.append(self._orderby)
  132. if self._limit is not None:
  133. sql_list.append(self._limit)
  134. return "%s;" % ' '.join(sql_list)
  135. def reset(self):
  136. """Clean internal variables"""
  137. self._select = None
  138. self._where = None
  139. self._orderby = None
  140. self._limit = None
  141. self._groupby = None
  142. class Columns(object):
  143. """Object to work with columns table.
  144. It is possible to instantiate a Columns object given the table name and
  145. the database connection.
  146. For a sqlite table:
  147. >>> import sqlite3
  148. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
  149. >>> cols_sqlite = Columns(test_vector_name,
  150. ... sqlite3.connect(get_path(path)))
  151. >>> cols_sqlite.tname
  152. 'table_doctest_map'
  153. For a postgreSQL table:
  154. >>> import psycopg2 as pg #doctest: +SKIP
  155. >>> cols_pg = Columns(test_vector_name,
  156. ... pg.connect('host=localhost dbname=grassdb')) #doctest: +SKIP
  157. >>> cols_pg.tname #doctest: +SKIP
  158. 'table_doctest_map' #doctest: +SKIP
  159. """
  160. def __init__(self, tname, connection, key='cat'):
  161. self.tname = tname
  162. self.conn = connection
  163. self.key = key
  164. self.odict = None
  165. self.update_odict()
  166. def __contains__(self, item):
  167. return item in self.names()
  168. def __repr__(self):
  169. return "Columns(%r)" % list(self.items())
  170. def __getitem__(self, key):
  171. return self.odict[key]
  172. def __setitem__(self, name, new_type):
  173. self.cast(name, new_type)
  174. self.update_odict(self)
  175. def __iter__(self):
  176. return self.odict.__iter__()
  177. def __len__(self):
  178. return self.odict.__len__()
  179. def __eq__(self, obj):
  180. """Return True if two table have the same columns.
  181. >>> import sqlite3
  182. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
  183. >>> connection = sqlite3.connect(get_path(path))
  184. >>> cols0 = Columns(test_vector_name, connection)
  185. >>> cols1 = Columns(test_vector_name, connection)
  186. >>> cols0 == cols1
  187. True
  188. """
  189. return obj.tname == self.tname and obj.odict == self.odict
  190. def __ne__(self, other):
  191. return not self == other
  192. # Restore Python 2 hashing beaviour on Python 3
  193. __hash__ = object.__hash__
  194. def is_pg(self):
  195. """Return True if is a psycopg connection.
  196. >>> import sqlite3
  197. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
  198. >>> cols_sqlite = Columns(test_vector_name,
  199. ... sqlite3.connect(get_path(path)))
  200. >>> cols_sqlite.is_pg()
  201. False
  202. >>> import psycopg2 as pg #doctest: +SKIP
  203. >>> cols_pg = Columns(test_vector_name,
  204. ... pg.connect('host=localhost dbname=grassdb')) #doctest: +SKIP
  205. >>> cols_pg.is_pg() #doctest: +SKIP
  206. True
  207. """
  208. return hasattr(self.conn, 'xid')
  209. def update_odict(self):
  210. """Read columns name and types from table and update the odict
  211. attribute.
  212. """
  213. if self.is_pg():
  214. # is a postgres connection
  215. cur = self.conn.cursor()
  216. cur.execute("SELECT oid,typname FROM pg_type")
  217. diz = dict(cur.fetchall())
  218. odict = OrderedDict()
  219. import psycopg2 as pg
  220. try:
  221. cur.execute(sql.SELECT.format(cols='*', tname=self.tname))
  222. descr = cur.description
  223. for column in descr:
  224. name, ctype = column[:2]
  225. odict[name] = diz[ctype]
  226. except pg.ProgrammingError:
  227. pass
  228. self.odict = odict
  229. else:
  230. # is a sqlite connection
  231. cur = self.conn.cursor()
  232. cur.execute(sql.PRAGMA.format(tname=self.tname))
  233. descr = cur.fetchall()
  234. odict = OrderedDict()
  235. for column in descr:
  236. name, ctype = column[1:3]
  237. odict[name] = ctype
  238. self.odict = odict
  239. values = ','.join(['?', ] * self.__len__())
  240. kv = ','.join(['%s=?' % k for k in self.odict.keys() if k != self.key])
  241. where = "%s=?" % self.key
  242. self.insert_str = sql.INSERT.format(tname=self.tname, values=values)
  243. self.update_str = sql.UPDATE_WHERE.format(tname=self.tname,
  244. values=kv, condition=where)
  245. def sql_descr(self, remove=None):
  246. """Return a string with description of columns.
  247. Remove it is used to remove a columns.
  248. >>> import sqlite3
  249. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
  250. >>> cols_sqlite = Columns(test_vector_name,
  251. ... sqlite3.connect(get_path(path)))
  252. >>> cols_sqlite.sql_descr() # doctest: +ELLIPSIS
  253. 'cat INTEGER, name varchar(50), value double precision'
  254. >>> import psycopg2 as pg # doctest: +SKIP
  255. >>> cols_pg = Columns(test_vector_name,
  256. ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
  257. >>> cols_pg.sql_descr() # doctest: +ELLIPSIS +SKIP
  258. 'cat INTEGER, name varchar(50), value double precision'
  259. """
  260. if remove:
  261. return ', '.join(['%s %s' % (key, val) for key, val in self.items()
  262. if key != remove])
  263. else:
  264. return ', '.join(['%s %s' % (key, val)
  265. for key, val in self.items()])
  266. def types(self):
  267. """Return a list with the column types.
  268. >>> import sqlite3
  269. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
  270. >>> cols_sqlite = Columns(test_vector_name,
  271. ... sqlite3.connect(get_path(path)))
  272. >>> cols_sqlite.types() # doctest: +ELLIPSIS
  273. ['INTEGER', 'varchar(50)', 'double precision']
  274. >>> import psycopg2 as pg # doctest: +SKIP
  275. >>> cols_pg = Columns(test_vector_name,
  276. ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
  277. >>> cols_pg.types() # doctest: +ELLIPSIS +SKIP
  278. ['INTEGER', 'varchar(50)', 'double precision']
  279. """
  280. return self.odict.values()
  281. def names(self, remove=None, unicod=True):
  282. """Return a list with the column names.
  283. Remove it is used to remove a columns.
  284. >>> import sqlite3
  285. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
  286. >>> cols_sqlite = Columns(test_vector_name,
  287. ... sqlite3.connect(get_path(path)))
  288. >>> cols_sqlite.names() # doctest: +ELLIPSIS
  289. ['cat', 'name', 'value']
  290. >>> import psycopg2 as pg # doctest: +SKIP
  291. >>> cols_pg = Columns(test_vector_name, # doctest: +SKIP
  292. ... pg.connect('host=localhost dbname=grassdb'))
  293. >>> cols_pg.names() # doctest: +ELLIPSIS +SKIP
  294. ['cat', 'name', 'value']
  295. """
  296. if remove:
  297. nams = self.odict.keys()
  298. nams.remove(remove)
  299. else:
  300. nams = self.odict.keys()
  301. if unicod:
  302. return nams
  303. else:
  304. return [str(name) for name in nams]
  305. def items(self):
  306. """Return a list of tuple with column name and column type.
  307. >>> import sqlite3
  308. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
  309. >>> cols_sqlite = Columns(test_vector_name,
  310. ... sqlite3.connect(get_path(path)))
  311. >>> cols_sqlite.items() # doctest: +ELLIPSIS
  312. [('cat', 'INTEGER'), ('name', 'varchar(50)'), ('value', 'double precision')]
  313. >>> import psycopg2 as pg # doctest: +SKIP
  314. >>> cols_pg = Columns(test_vector_name,
  315. ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
  316. >>> cols_pg.items() # doctest: +ELLIPSIS +SKIP
  317. [('cat', 'INTEGER'), ('name', 'varchar(50)'), ('value', 'double precision')]
  318. """
  319. return self.odict.items()
  320. def add(self, col_name, col_type):
  321. """Add a new column to the table.
  322. :param col_name: the name of column to add
  323. :type col_name: str
  324. :param col_type: the tipe of column to add
  325. :type col_type: str
  326. >>> import sqlite3
  327. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
  328. >>> from grass.pygrass.utils import copy, remove
  329. >>> copy(test_vector_name,'mycensus','vect')
  330. >>> cols_sqlite = Columns('mycensus',
  331. ... sqlite3.connect(get_path(path)))
  332. >>> cols_sqlite.add(['n_pizza'], ['INT'])
  333. >>> 'n_pizza' in cols_sqlite
  334. True
  335. >>> import psycopg2 as pg # doctest: +SKIP
  336. >>> cols_pg = Columns('boundary_municp_pg',
  337. ... pg.connect('host=localhost dbname=grassdb')) #doctest: +SKIP
  338. >>> cols_pg.add('n_pizza', 'INT') # doctest: +SKIP
  339. >>> 'n_pizza' in cols_pg # doctest: +SKIP
  340. True
  341. >>> remove('mycensus', 'vect')
  342. """
  343. def check(col_type):
  344. """Check the column type if it is supported by GRASS
  345. :param col_type: the type of column
  346. :type col_type: str
  347. """
  348. valid_type = ('DOUBLE PRECISION', 'DOUBLE', 'INT', 'INTEGER',
  349. 'DATE', 'VARCHAR')
  350. col = col_type.upper()
  351. valid = [col.startswith(tp) for tp in valid_type]
  352. if not any(valid):
  353. str_err = ("Type: %r is not supported."
  354. "\nSupported types are: %s")
  355. raise TypeError(str_err % (col_type, ", ".join(valid_type)))
  356. return col_type
  357. col_type = ([check(col_type), ] if isinstance(col_type, (str, unicode))
  358. else [check(col) for col in col_type])
  359. col_name = ([col_name, ] if isinstance(col_name, (str, unicode))
  360. else col_name)
  361. sqlcode = [sql.ADD_COL.format(tname=self.tname, cname=cn, ctype=ct)
  362. for cn, ct in zip(col_name, col_type)]
  363. cur = self.conn.cursor()
  364. cur.executescript('\n'.join(sqlcode))
  365. self.conn.commit()
  366. cur.close()
  367. self.update_odict()
  368. def rename(self, old_name, new_name):
  369. """Rename a column of the table.
  370. :param old_name: the name of existing column
  371. :type old_name: str
  372. :param new_name: the name of new column
  373. :type new_name: str
  374. >>> import sqlite3
  375. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
  376. >>> from grass.pygrass.utils import copy, remove
  377. >>> copy(test_vector_name,'mycensus','vect')
  378. >>> cols_sqlite = Columns('mycensus',
  379. ... sqlite3.connect(get_path(path)))
  380. >>> cols_sqlite.add(['n_pizza'], ['INT'])
  381. >>> 'n_pizza' in cols_sqlite
  382. True
  383. >>> cols_sqlite.rename('n_pizza', 'n_pizzas') # doctest: +ELLIPSIS
  384. >>> 'n_pizza' in cols_sqlite
  385. False
  386. >>> 'n_pizzas' in cols_sqlite
  387. True
  388. >>> import psycopg2 as pg # doctest: +SKIP
  389. >>> cols_pg = Columns(test_vector_name,
  390. ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
  391. >>> cols_pg.rename('n_pizza', 'n_pizzas') # doctest: +SKIP
  392. >>> 'n_pizza' in cols_pg # doctest: +SKIP
  393. False
  394. >>> 'n_pizzas' in cols_pg # doctest: +SKIP
  395. True
  396. >>> remove('mycensus', 'vect')
  397. """
  398. cur = self.conn.cursor()
  399. if self.is_pg():
  400. cur.execute(sql.RENAME_COL.format(tname=self.tname,
  401. old_name=old_name,
  402. new_name=new_name))
  403. self.conn.commit()
  404. cur.close()
  405. self.update_odict()
  406. else:
  407. cur.execute(sql.ADD_COL.format(tname=self.tname,
  408. cname=new_name,
  409. ctype=str(self.odict[old_name])))
  410. cur.execute(sql.UPDATE.format(tname=self.tname,
  411. new_col=new_name,
  412. old_col=old_name))
  413. self.conn.commit()
  414. cur.close()
  415. self.update_odict()
  416. self.drop(old_name)
  417. def cast(self, col_name, new_type):
  418. """Change the column type.
  419. :param col_name: the name of column
  420. :type col_name: str
  421. :param new_type: the new type of column
  422. :type new_type: str
  423. >>> import sqlite3
  424. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
  425. >>> from grass.pygrass.utils import copy, remove
  426. >>> copy(test_vector_name,'mycensus','vect')
  427. >>> cols_sqlite = Columns('mycensus',
  428. ... sqlite3.connect(get_path(path)))
  429. >>> cols_sqlite.add(['n_pizzas'], ['INT'])
  430. >>> cols_sqlite.cast('n_pizzas', 'float8') # doctest: +ELLIPSIS
  431. Traceback (most recent call last):
  432. ...
  433. DBError: SQLite does not support to cast columns.
  434. >>> import psycopg2 as pg # doctest: +SKIP
  435. >>> cols_pg = Columns(test_vector_name,
  436. ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
  437. >>> cols_pg.cast('n_pizzas', 'float8') # doctest: +SKIP
  438. >>> cols_pg['n_pizzas'] # doctest: +SKIP
  439. 'float8'
  440. >>> remove('mycensus', 'vect')
  441. .. warning ::
  442. It is not possible to cast a column with sqlite
  443. """
  444. if self.is_pg():
  445. cur = self.conn.cursor()
  446. cur.execute(sql.CAST_COL.format(tname=self.tname, col=col_name,
  447. ctype=new_type))
  448. self.conn.commit()
  449. cur.close()
  450. self.update_odict()
  451. else:
  452. # sqlite does not support rename columns:
  453. raise DBError('SQLite does not support to cast columns.')
  454. def drop(self, col_name):
  455. """Drop a column from the table.
  456. :param col_name: the name of column to remove
  457. :type col_name: str
  458. >>> import sqlite3
  459. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
  460. >>> from grass.pygrass.utils import copy, remove
  461. >>> copy(test_vector_name,'mycensus','vect')
  462. >>> cols_sqlite = Columns('mycensus',
  463. ... sqlite3.connect(get_path(path)))
  464. >>> cols_sqlite.drop('name') # doctest: +ELLIPSIS
  465. >>> 'name' in cols_sqlite
  466. False
  467. >>> import psycopg2 as pg # doctest: +SKIP
  468. >>> cols_pg = Columns(test_vector_name,
  469. ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
  470. >>> cols_pg.drop('name') # doctest: +SKIP
  471. >>> 'name' in cols_pg # doctest: +SKIP
  472. False
  473. >>> remove('mycensus','vect')
  474. """
  475. cur = self.conn.cursor()
  476. if self.is_pg():
  477. cur.execute(sql.DROP_COL.format(tname=self.tname,
  478. cname=col_name))
  479. else:
  480. desc = str(self.sql_descr(remove=col_name))
  481. names = ', '.join(self.names(remove=col_name, unicod=False))
  482. queries = sql.DROP_COL_SQLITE.format(tname=self.tname,
  483. keycol=self.key,
  484. coldef=desc,
  485. colnames=names).split('\n')
  486. for query in queries:
  487. cur.execute(query)
  488. self.conn.commit()
  489. cur.close()
  490. self.update_odict()
  491. class Link(object):
  492. """Define a Link between vector map and the attributes table.
  493. It is possible to define a Link object or given all the information
  494. (layer, name, table name, key, database, driver):
  495. >>> link = Link(1, 'link0', test_vector_name, 'cat',
  496. ... '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db', 'sqlite')
  497. >>> link.layer
  498. 1
  499. >>> link.name
  500. 'link0'
  501. >>> link.table_name
  502. 'table_doctest_map'
  503. >>> link.key
  504. 'cat'
  505. >>> link.database
  506. '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
  507. >>> link.driver
  508. 'sqlite'
  509. >>> link
  510. Link(1, link0, sqlite)
  511. It is possible to change parameters with:
  512. >>> link.driver = 'pg' # doctest: +SKIP
  513. >>> link.driver # doctest: +SKIP
  514. 'pg'
  515. >>> link.driver = 'postgres' # doctest: +ELLIPSIS +SKIP
  516. Traceback (most recent call last):
  517. ...
  518. TypeError: Driver not supported, use: sqlite, pg.
  519. >>> link.driver # doctest: +SKIP
  520. 'pg'
  521. >>> link.number = 0 # doctest: +ELLIPSIS +SKIP
  522. Traceback (most recent call last):
  523. ...
  524. TypeError: Number must be positive and greater than 0.
  525. Or given a c_fieldinfo object that is a ctypes pointer to the field_info C
  526. struct. ::
  527. >>> link = Link(c_fieldinfo = ctypes.pointer(libvect.field_info()))
  528. """
  529. def _get_layer(self):
  530. return self.c_fieldinfo.contents.number
  531. def _set_layer(self, number):
  532. if number <= 0:
  533. raise TypeError("Number must be positive and greater than 0.")
  534. self.c_fieldinfo.contents.number = number
  535. layer = property(fget=_get_layer, fset=_set_layer,
  536. doc="Set and obtain layer number")
  537. def _get_name(self):
  538. return decode(self.c_fieldinfo.contents.name)
  539. def _set_name(self, name):
  540. self.c_fieldinfo.contents.name = String(name)
  541. name = property(fget=_get_name, fset=_set_name,
  542. doc="Set and obtain name vale")
  543. def _get_table(self):
  544. return decode(self.c_fieldinfo.contents.table)
  545. def _set_table(self, new_name):
  546. self.c_fieldinfo.contents.table = String(new_name)
  547. table_name = property(fget=_get_table, fset=_set_table,
  548. doc="Set and obtain table name value")
  549. def _get_key(self):
  550. return decode(self.c_fieldinfo.contents.key)
  551. def _set_key(self, key):
  552. self.c_fieldinfo.contents.key = String(key)
  553. key = property(fget=_get_key, fset=_set_key,
  554. doc="Set and obtain cat value")
  555. def _get_database(self):
  556. return decode(self.c_fieldinfo.contents.database)
  557. def _set_database(self, database):
  558. self.c_fieldinfo.contents.database = String(database)
  559. database = property(fget=_get_database, fset=_set_database,
  560. doc="Set and obtain database value")
  561. def _get_driver(self):
  562. return decode(self.c_fieldinfo.contents.driver)
  563. def _set_driver(self, driver):
  564. if driver not in ('sqlite', 'pg'):
  565. str_err = "Driver not supported, use: %s." % ", ".join(DRIVERS)
  566. raise TypeError(str_err)
  567. self.c_fieldinfo.contents.driver = String(driver)
  568. driver = property(fget=_get_driver, fset=_set_driver,
  569. doc="Set and obtain driver value. The drivers supported \
  570. by PyGRASS are: SQLite and PostgreSQL")
  571. def __init__(self, layer=1, name=None, table=None, key='cat',
  572. database='$GISDBASE/$LOCATION_NAME/'
  573. '$MAPSET/sqlite/sqlite.db',
  574. driver='sqlite', c_fieldinfo=None):
  575. if c_fieldinfo is not None:
  576. self.c_fieldinfo = c_fieldinfo
  577. else:
  578. self.c_fieldinfo = ctypes.pointer(libvect.field_info())
  579. self.layer = layer
  580. self.name = name
  581. self.table_name = table
  582. self.key = key
  583. self.database = database
  584. self.driver = driver
  585. def __repr__(self):
  586. return "Link(%d, %s, %s)" % (self.layer, self.name, self.driver)
  587. def __eq__(self, link):
  588. """Return True if two Link instance have the same parameters.
  589. >>> l0 = Link(1, 'link0', test_vector_name, 'cat',
  590. ... '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db', 'sqlite')
  591. >>> l1 = Link(1, 'link0', test_vector_name, 'cat',
  592. ... '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db', 'sqlite')
  593. >>> l2 = Link(2, 'link0', test_vector_name, 'cat',
  594. ... '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db', 'sqlite')
  595. >>> l0 == l1
  596. True
  597. >>> l1 == l2
  598. False
  599. """
  600. attrs = ['layer', 'name', 'table_name', 'key', 'driver']
  601. for attr in attrs:
  602. if getattr(self, attr) != getattr(link, attr):
  603. return False
  604. return True
  605. def __ne__(self, other):
  606. return not self == other
  607. # Restore Python 2 hashing beaviour on Python 3
  608. __hash__ = object.__hash__
  609. def connection(self):
  610. """Return a connection object.
  611. >>> link = Link(1, 'link0', test_vector_name, 'cat',
  612. ... '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db',
  613. ... 'sqlite')
  614. >>> conn = link.connection()
  615. >>> cur = conn.cursor()
  616. >>> link.table_name
  617. 'table_doctest_map'
  618. >>> cur.execute("SELECT cat, name, value from %s" %
  619. ... link.table_name) # doctest: +ELLIPSIS
  620. <sqlite3.Cursor object at ...>
  621. >>> cur.fetchone() #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  622. (1, 'point', 1.0)
  623. >>> cur.close()
  624. >>> conn.close()
  625. """
  626. driver = self.driver
  627. if 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 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('SELECT cat, name, value FROM table_doctest_map;')
  660. >>> cur = table.execute()
  661. >>> cur.fetchone()
  662. (1, '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. '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('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('SELECT cat, name FROM table_doctest_map ORDER BY value;')
  904. >>> cur = tab_sqlite.execute()
  905. >>> cur.fetchone() #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  906. (1, '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)