table.py 41 KB

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