table.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  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. import ctypes
  11. import numpy as np
  12. from sqlite3 import OperationalError
  13. try:
  14. from collections import OrderedDict
  15. except:
  16. from grass.pygrass.orderdict import OrderedDict
  17. import grass.lib.vector as libvect
  18. from grass.pygrass.gis import Mapset
  19. from grass.exceptions import DBError
  20. from grass.pygrass.utils import table_exist, decode
  21. from grass.script.db import db_table_in_vector
  22. from grass.script.core import warning
  23. from grass.pygrass.vector import sql
  24. from grass.lib.ctypes_preamble import String
  25. if sys.version_info.major >= 3:
  26. long = int
  27. unicode = str
  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 list(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 = list(self.odict.keys())
  298. nams.remove(remove)
  299. else:
  300. nams = list(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 list(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. grass.exceptions.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)