table.py 41 KB

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