table.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Wed Aug 8 15:29:21 2012
  4. @author: pietro
  5. """
  6. import ctypes
  7. try:
  8. from collections import OrderedDict
  9. except:
  10. from pygrass.orderdict import OrderedDict
  11. import grass.lib.vector as libvect
  12. import grass.script.core as core
  13. import sql
  14. DRIVERS = ('sqlite', 'pg')
  15. class DBError(Exception):
  16. def __init__(self, value):
  17. self.value = value
  18. def __str__(self):
  19. return repr(self.value)
  20. def get_path(path):
  21. if "$" not in path:
  22. return path
  23. else:
  24. grassenv = core.gisenv()
  25. path = path.replace('$GISDBASE', grassenv['GISDBASE'])
  26. path = path.replace('$LOCATION_NAME', grassenv['LOCATION_NAME'])
  27. path = path.replace('$MAPSET', grassenv['MAPSET'])
  28. return path
  29. class Filters(object):
  30. """Help user to build a simple sql query. ::
  31. >>> filter = Filters('table')
  32. >>> filter.get_sql()
  33. 'SELECT * FROM table;'
  34. >>> filter.where("area<10000").get_sql()
  35. 'SELECT * FROM table WHERE area<10000;'
  36. >>> filter.select("cat", "area").get_sql()
  37. 'SELECT cat, area FROM table WHERE area<10000;'
  38. >>> filter.order_by("area").limit(10).get_sql()
  39. 'SELECT cat, area FROM table WHERE area<10000 ORDER BY area LIMIT 10;'
  40. ..
  41. """
  42. def __init__(self, tname):
  43. self.tname = tname
  44. self._select = None
  45. self._where = None
  46. self._orderby = None
  47. self._limit = None
  48. def __repr__(self):
  49. return "Filters(%r)" % self.get_sql()
  50. def select(self, *args):
  51. cols = ', '.join(args) if args else '*'
  52. select = sql.SELECT[:-1]
  53. self._select = select.format(cols=cols, tname=self.tname)
  54. return self
  55. def where(self, condition):
  56. self._where = 'WHERE {condition}'.format(condition=condition)
  57. return self
  58. def order_by(self, orderby):
  59. if not isinstance(orderby, str):
  60. orderby = ', '.join(orderby)
  61. self._orderby = 'ORDER BY {orderby}'.format(orderby=orderby)
  62. return self
  63. def limit(self, number):
  64. if not isinstance(number, int):
  65. raise ValueError("Must be an integer.")
  66. else:
  67. self._limit = 'LIMIT {number}'.format(number=number)
  68. return self
  69. def get_sql(self):
  70. sql_list = list()
  71. if self._select is None:
  72. self.select()
  73. sql_list.append(self._select)
  74. if self._where is not None:
  75. sql_list.append(self._where)
  76. if self._orderby is not None:
  77. sql_list.append(self._orderby)
  78. if self._limit is not None:
  79. sql_list.append(self._limit)
  80. return "%s;" % ' '.join(sql_list)
  81. def reset(self):
  82. self._select = None
  83. self._where = None
  84. self._orderby = None
  85. self._limit = None
  86. class Columns(object):
  87. """Object to work with columns table.
  88. It is possible to instantiate a Columns object given the table name and
  89. the database connection.
  90. For a sqlite table: ::
  91. >>> import sqlite3
  92. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  93. >>> cols_sqlite = Columns('boundary_municp_sqlite',
  94. ... sqlite3.connect(get_path(path)))
  95. >>> cols_sqlite.tname
  96. 'boundary_municp_sqlite'
  97. For a postgreSQL table: ::
  98. >>> import psycopg2 as pg
  99. >>> cols_pg = Columns('boundary_municp_pg',
  100. ... pg.connect('host=localhost dbname=grassdb'))
  101. >>> cols_pg.tname
  102. 'boundary_municp_pg'
  103. ..
  104. """
  105. def __init__(self, tname, connection, key='cat'):
  106. self.tname = tname
  107. self.conn = connection
  108. self.key = key
  109. self.odict = None
  110. self.update_odict()
  111. def __contains__(self, item):
  112. return item in self.names()
  113. def __repr__(self):
  114. return "Columns(%r)" % self.items()
  115. def __getitem__(self, key):
  116. return self.odict[key]
  117. def __setitem__(self, name, new_type):
  118. self.cast(name, new_type)
  119. self.update_odict(self)
  120. def __iter__(self):
  121. return self.odict.__iter__()
  122. def __len__(self):
  123. return self.odict.__len__()
  124. def __eq__(self, obj):
  125. return obj.tname == self.tname and obj.odict == self.odict
  126. def is_pg(self):
  127. """Return True if is a psycopg connection. ::
  128. >>> import sqlite3
  129. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  130. >>> cols_sqlite = Columns('boundary_municp_sqlite',
  131. ... sqlite3.connect(get_path(path)))
  132. >>> cols_sqlite.is_pg()
  133. False
  134. >>> import psycopg2 as pg
  135. >>> cols_pg = Columns('boundary_municp_pg',
  136. ... pg.connect('host=localhost dbname=grassdb'))
  137. >>> cols_pg.is_pg()
  138. True
  139. ..
  140. """
  141. return hasattr(self.conn, 'xid')
  142. def update_odict(self):
  143. """Read columns name and types from table and update the odict
  144. attribute.
  145. """
  146. if self.is_pg():
  147. # is a postgres connection
  148. cur = self.conn.cursor()
  149. cur.execute("SELECT oid,typname FROM pg_type")
  150. diz = dict(cur.fetchall())
  151. cur.execute(sql.SELECT.format(cols='*', tname=self.tname))
  152. descr = cur.description
  153. odict = OrderedDict()
  154. for column in descr:
  155. name, ctype = column[:2]
  156. odict[name] = diz[ctype]
  157. self.odict = odict
  158. else:
  159. # is a sqlite connection
  160. cur = self.conn.cursor()
  161. cur.execute(sql.PRAGMA.format(tname=self.tname))
  162. descr = cur.fetchall()
  163. odict = OrderedDict()
  164. for column in descr:
  165. name, ctype = column[1:3]
  166. odict[name] = ctype
  167. self.odict = odict
  168. values = ','.join(['?', ] * self.__len__())
  169. self.insert_str = sql.INSERT.format(tname=self.tname, values=values)
  170. def sql_descr(self, remove=None):
  171. """Return a string with description of columns.
  172. Remove it is used to remove a columns.::
  173. >>> import sqlite3
  174. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  175. >>> cols_sqlite = Columns('boundary_municp_sqlite',
  176. ... sqlite3.connect(get_path(path)))
  177. >>> cols_sqlite.sql_descr() # doctest: +ELLIPSIS
  178. u'cat integer, OBJECTID integer, AREA double precision, ...'
  179. >>> import psycopg2 as pg
  180. >>> cols_pg = Columns('boundary_municp_pg',
  181. ... pg.connect('host=localhost dbname=grassdb'))
  182. >>> cols_pg.sql_descr() # doctest: +ELLIPSIS
  183. 'cat int4, objectid int4, area float8, perimeter float8, ...'
  184. """
  185. if remove:
  186. return ', '.join(['%s %s' % (key, val) for key, val in self.items()
  187. if key != remove])
  188. else:
  189. return ', '.join(['%s %s' % (key, val)
  190. for key, val in self.items()])
  191. def types(self):
  192. """Return a list with the column types. ::
  193. >>> import sqlite3
  194. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  195. >>> cols_sqlite = Columns('boundary_municp_sqlite',
  196. ... sqlite3.connect(get_path(path)))
  197. >>> cols_sqlite.types() # doctest: +ELLIPSIS
  198. [u'integer', u'integer', ...]
  199. >>> import psycopg2 as pg
  200. >>> cols_pg = Columns('boundary_municp_pg',
  201. ... pg.connect('host=localhost dbname=grassdb'))
  202. >>> cols_pg.types() # doctest: +ELLIPSIS
  203. ['int4', 'int4', 'float8', 'float8', 'float8', ...]
  204. ..
  205. """
  206. return self.odict.values()
  207. def names(self, remove=None, unicod=True):
  208. """Return a list with the column names.
  209. Remove it is used to remove a columns.::
  210. >>> import sqlite3
  211. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  212. >>> cols_sqlite = Columns('boundary_municp_sqlite',
  213. ... sqlite3.connect(get_path(path)))
  214. >>> cols_sqlite.names() # doctest: +ELLIPSIS
  215. [u'cat', u'OBJECTID', u'AREA', u'PERIMETER', ...]
  216. >>> import psycopg2 as pg
  217. >>> cols_pg = Columns('boundary_municp_pg',
  218. ... pg.connect('host=localhost dbname=grassdb'))
  219. >>> cols_pg.names() # doctest: +ELLIPSIS
  220. ['cat', 'objectid', 'area', 'perimeter', ...]
  221. ..
  222. """
  223. if remove:
  224. nams = self.odict.keys()
  225. nams.remove(remove)
  226. else:
  227. nams = self.odict.keys()
  228. if unicod:
  229. return nams
  230. else:
  231. return [str(name) for name in nams]
  232. def items(self):
  233. """Return a list of tuple with column name and column type. ::
  234. >>> import sqlite3
  235. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  236. >>> cols_sqlite = Columns('boundary_municp_sqlite',
  237. ... sqlite3.connect(get_path(path)))
  238. >>> cols_sqlite.items() # doctest: +ELLIPSIS
  239. [(u'cat', u'integer'), ...]
  240. >>> import psycopg2 as pg
  241. >>> cols_pg = Columns('boundary_municp_pg',
  242. ... pg.connect('host=localhost dbname=grassdb'))
  243. >>> cols_pg.items() # doctest: +ELLIPSIS
  244. [('cat', 'int4'), ('objectid', 'int4'), ('area', 'float8'), ...]
  245. ..
  246. """
  247. return self.odict.items()
  248. def create(self, cols):
  249. """"""
  250. cur = self.conn.cursor()
  251. coldef = ',\n'.join(['%s %s' % col for col in cols])
  252. cur.execute(sql.CREATE_TAB.format(tname=self.tname, coldef=coldef))
  253. self.conn.commit()
  254. cur.close()
  255. self.update_odict()
  256. def add(self, col_name, col_type):
  257. """Add a new column to the table. ::
  258. >>> import sqlite3
  259. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  260. >>> cols_sqlite = Columns('boundary_municp_sqlite',
  261. ... sqlite3.connect(get_path(path)))
  262. >>> cols_sqlite.add('n_pizza', 'int4')
  263. >>> 'n_pizza' in cols_sqlite
  264. True
  265. >>> import psycopg2 as pg
  266. >>> cols_pg = Columns('boundary_municp_pg',
  267. ... pg.connect('host=localhost dbname=grassdb'))
  268. >>> cols_pg.add('n_pizza', 'int4')
  269. >>> 'n_pizza' in cols_pg
  270. True
  271. ..
  272. """
  273. valid_type = ('DOUBLE PRECISION', 'INT', 'DATE')
  274. if 'VARCHAR' in col_type or col_type.upper() not in valid_type:
  275. str_err = "Type is not supported, supported types are: %s"
  276. raise TypeError(str_err % ", ".join(valid_type))
  277. cur = self.conn.cursor()
  278. cur.execute(sql.ADD_COL.format(tname=self.tname,
  279. cname=col_name,
  280. ctype=col_type))
  281. self.conn.commit()
  282. cur.close()
  283. self.update_odict()
  284. def rename(self, old_name, new_name):
  285. """Rename a column of the table. ::
  286. >>> import sqlite3
  287. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  288. >>> cols_sqlite = Columns('boundary_municp_sqlite',
  289. ... sqlite3.connect(get_path(path)))
  290. >>> cols_sqlite.rename('n_pizza', 'n_pizzas') # doctest: +ELLIPSIS
  291. >>> 'n_pizza' in cols_sqlite
  292. False
  293. >>> 'n_pizzas' in cols_sqlite
  294. True
  295. >>> import psycopg2 as pg
  296. >>> cols_pg = Columns('boundary_municp_pg',
  297. ... pg.connect('host=localhost dbname=grassdb'))
  298. >>> cols_pg.rename('n_pizza', 'n_pizzas')
  299. >>> 'n_pizza' in cols_pg
  300. False
  301. >>> 'n_pizzas' in cols_pg
  302. True
  303. ..
  304. """
  305. cur = self.conn.cursor()
  306. if self.is_pg():
  307. cur.execute(sql.RENAME_COL.format(tname=self.tname,
  308. old_name=old_name,
  309. new_name=new_name))
  310. self.conn.commit()
  311. cur.close()
  312. self.update_odict()
  313. else:
  314. cur.execute(sql.ADD_COL.format(tname=self.tname,
  315. cname=new_name,
  316. ctype=str(self.odict[old_name])))
  317. cur.execute(sql.UPDATE.format(tname=self.tname,
  318. new_col=new_name,
  319. old_col=old_name))
  320. self.conn.commit()
  321. cur.close()
  322. self.update_odict()
  323. self.drop(old_name)
  324. def cast(self, col_name, new_type):
  325. """Change the column type. ::
  326. >>> import sqlite3
  327. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  328. >>> cols_sqlite = Columns('boundary_municp_sqlite',
  329. ... sqlite3.connect(get_path(path)))
  330. >>> cols_sqlite.cast('n_pizzas', 'float8') # doctest: +ELLIPSIS
  331. Traceback (most recent call last):
  332. ...
  333. DBError: 'SQLite does not support to cast columns.'
  334. >>> import psycopg2 as pg
  335. >>> cols_pg = Columns('boundary_municp_pg',
  336. ... pg.connect('host=localhost dbname=grassdb'))
  337. >>> cols_pg.cast('n_pizzas', 'float8')
  338. >>> cols_pg['n_pizzas']
  339. 'float8'
  340. .. warning ::
  341. It is not possible to cast a column with sqlite
  342. ..
  343. """
  344. if self.is_pg():
  345. cur = self.conn.cursor()
  346. cur.execute(sql.CAST_COL.format(tname=self.tname, col=col_name,
  347. ctype=new_type))
  348. self.conn.commit()
  349. cur.close()
  350. self.update_odict()
  351. else:
  352. # sqlite does not support rename columns:
  353. raise DBError('SQLite does not support to cast columns.')
  354. def drop(self, col_name):
  355. """Drop a column from the table. ::
  356. >>> import sqlite3
  357. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  358. >>> cols_sqlite = Columns('boundary_municp_sqlite',
  359. ... sqlite3.connect(get_path(path)))
  360. >>> cols_sqlite.drop('n_pizzas') # doctest: +ELLIPSIS
  361. >>> 'n_pizzas' in cols_sqlite
  362. False
  363. >>> import psycopg2 as pg
  364. >>> cols_pg = Columns('boundary_municp_pg',
  365. ... pg.connect('host=localhost dbname=grassdb'))
  366. >>> cols_pg.drop('n_pizzas')
  367. >>> 'n_pizzas' in cols_pg
  368. False
  369. ..
  370. """
  371. cur = self.conn.cursor()
  372. if self.is_pg():
  373. cur.execute(sql.DROP_COL.format(tname=self.tname,
  374. cname=col_name))
  375. else:
  376. desc = str(self.sql_descr(remove=col_name))
  377. names = ', '.join(self.names(remove=col_name, unicod=False))
  378. queries = sql.DROP_COL_SQLITE.format(tname=self.tname,
  379. keycol=self.key,
  380. coldef=desc,
  381. colnames=names).split('\n')
  382. for query in queries:
  383. cur.execute(query)
  384. self.conn.commit()
  385. cur.close()
  386. self.update_odict()
  387. class Link(object):
  388. """Define a Link between vector map and the attributes table.
  389. It is possible to define a Link object or given all the information
  390. (layer, name, table name, key, database, driver): ::
  391. >>> link = Link(1, 'link0', 'boundary_municp_sqlite', 'cat',
  392. ... '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db', 'sqlite')
  393. >>> link.number
  394. 1
  395. >>> link.name
  396. 'link0'
  397. >>> link.table_name
  398. 'boundary_municp_sqlite'
  399. >>> link.key
  400. 'cat'
  401. >>> link.database
  402. '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  403. >>> link.driver
  404. 'sqlite'
  405. >>> link
  406. Link(1, link0, sqlite)
  407. It is possible to change parameters with: ::
  408. >>> link.driver = 'pg'
  409. >>> link.driver
  410. 'pg'
  411. >>> link.driver = 'postgres' # doctest: +ELLIPSIS
  412. Traceback (most recent call last):
  413. ...
  414. TypeError: Driver not supported, use: sqlite, pg.
  415. >>> link.driver
  416. 'pg'
  417. >>> link.number = 0 # doctest: +ELLIPSIS
  418. Traceback (most recent call last):
  419. ...
  420. TypeError: Number must be positive and greater than 0.
  421. Or given a c_fieldinfo object that is a ctypes pointer to the field_info C
  422. struct. ::
  423. >>> link = Link(c_fieldinfo = ctypes.pointer(libvect.field_info()))
  424. ..
  425. """
  426. def _get_layer(self):
  427. return self.c_fieldinfo.contents.number
  428. def _set_layer(self, number):
  429. if number <= 0:
  430. raise TypeError("Number must be positive and greater than 0.")
  431. self.c_fieldinfo.contents.number = number
  432. layer = property(fget=_get_layer, fset=_set_layer)
  433. def _get_name(self):
  434. return self.c_fieldinfo.contents.name
  435. def _set_name(self, name):
  436. self.c_fieldinfo.contents.name = name
  437. name = property(fget=_get_name, fset=_set_name)
  438. def _get_table(self):
  439. return self.c_fieldinfo.contents.table
  440. def _set_table(self, new_name):
  441. self.c_fieldinfo.contents.table = new_name
  442. table_name = property(fget=_get_table, fset=_set_table)
  443. def _get_key(self):
  444. return self.c_fieldinfo.contents.key
  445. def _set_key(self, key):
  446. self.c_fieldinfo.contents.key = key
  447. key = property(fget=_get_key, fset=_set_key)
  448. def _get_database(self):
  449. return self.c_fieldinfo.contents.database
  450. def _set_database(self, database):
  451. self.c_fieldinfo.contents.database = database
  452. database = property(fget=_get_database, fset=_set_database)
  453. def _get_driver(self):
  454. return self.c_fieldinfo.contents.driver
  455. def _set_driver(self, driver):
  456. if driver not in ('sqlite', 'pg'):
  457. str_err = "Driver not supported, use: %s." % ", ".join(DRIVERS)
  458. raise TypeError(str_err)
  459. self.c_fieldinfo.contents.driver = driver
  460. driver = property(fget=_get_driver, fset=_set_driver)
  461. def __init__(self, layer=1, name=None, table=None, key=None,
  462. database=None, driver=None, c_fieldinfo=None):
  463. if c_fieldinfo is not None:
  464. self.c_fieldinfo = c_fieldinfo
  465. else:
  466. self.c_fieldinfo = ctypes.pointer(libvect.field_info())
  467. self.layer = layer
  468. self.name = name
  469. self.table_name = table
  470. self.key = key
  471. self.database = database
  472. self.driver = driver
  473. def __repr__(self):
  474. return "Link(%d, %s, %s)" % (self.layer, self.name, self.driver)
  475. def connection(self):
  476. """Return a connection object. ::
  477. >>> link = Link(1, 'link0', 'boundary_municp_sqlite', 'cat',
  478. ... '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db',
  479. ... 'sqlite')
  480. >>> conn = link.connection()
  481. >>> cur = conn.cursor()
  482. >>> cur.execute("SELECT cat,COUNTY,PERIMETER FROM %s" %
  483. ... link.table_name) # doctest: +ELLIPSIS
  484. <sqlite3.Cursor object at ...>
  485. >>> cur.fetchone()
  486. (1, u'SURRY', 1415.331)
  487. >>> cur.close()
  488. >>> conn.close()
  489. ...
  490. """
  491. if self.driver == 'sqlite':
  492. import sqlite3
  493. return sqlite3.connect(get_path(self.database))
  494. elif self.driver == 'pg':
  495. try:
  496. import psycopg2
  497. db = ' '.join(self.database.split(','))
  498. return psycopg2.connect(db)
  499. except ImportError:
  500. er = "You need to install psycopg2 to connect with this table."
  501. raise ImportError(er)
  502. else:
  503. str_err = "Driver is not supported yet, pleas use: sqlite or pg"
  504. raise TypeError(str_err)
  505. def table(self):
  506. """Return a Table object. ::
  507. >>> link = Link(1, 'link0', 'boundary_municp_sqlite', 'cat',
  508. ... '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db',
  509. ... 'sqlite')
  510. >>> table = link.table()
  511. >>> table.filters.select('cat', 'COUNTY', 'PERIMETER')
  512. Filters('SELECT cat, COUNTY, PERIMETER FROM boundary_municp_sqlite;')
  513. >>> cur = table.execute()
  514. >>> cur.fetchone()
  515. (1, u'SURRY', 1415.331)
  516. >>> cur.close()
  517. ..
  518. """
  519. return Table(self.table_name, self.connection(), self.key)
  520. def info(self):
  521. """Print information of the link. ::
  522. >>> link = Link(1, 'link0', 'boundary_municp_sqlite', 'cat',
  523. ... '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db',
  524. ... 'sqlite')
  525. >>> link.info()
  526. layer: 1
  527. name: link0
  528. table: boundary_municp_sqlite
  529. key: cat
  530. database: $GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db
  531. driver: sqlite
  532. ..
  533. """
  534. print "layer: ", self.layer
  535. print "name: ", self.name
  536. print "table: ", self.table_name
  537. print "key: ", self.key
  538. print "database: ", self.database
  539. print "driver: ", self.driver
  540. class DBlinks(object):
  541. """Interface containing link to the table DB. ::
  542. >>> from pygrass.vector import VectorTopo
  543. >>> municip = VectorTopo('boundary_municp_sqlite')
  544. >>> municip.open()
  545. >>> dblinks = DBlinks(municip.c_mapinfo)
  546. >>> dblinks
  547. DBlinks([Link(1, boundary_municp, sqlite)])
  548. >>> dblinks[1]
  549. Link(1, boundary_municp, sqlite)
  550. >>> dblinks[0] # doctest: +ELLIPSIS
  551. Traceback (most recent call last):
  552. ...
  553. TypeError: The index must be != 0.
  554. >>> dblinks['boundary_municp']
  555. Link(1, boundary_municp, sqlite)
  556. ..
  557. """
  558. def __init__(self, c_mapinfo):
  559. self.c_mapinfo = c_mapinfo
  560. def __len__(self):
  561. return self.num_dblinks()
  562. def __iter__(self):
  563. return (self.by_index(i)
  564. for i in xrange(self.num_dblinks()))
  565. def __getitem__(self, item):
  566. """
  567. """
  568. if isinstance(item, int):
  569. return self.by_index(item)
  570. else:
  571. return self.by_name(item)
  572. def __repr__(self):
  573. return "DBlinks(%r)" % [link for link in self.__iter__()]
  574. def by_index(self, indx):
  575. c_fieldinfo = libvect.Vect_get_dblink(self.c_mapinfo, indx)
  576. return Link(c_fieldinfo=c_fieldinfo)
  577. def by_layer(self, layer):
  578. c_fieldinfo = libvect.Vect_get_field(self.c_mapinfo, layer)
  579. return Link(c_fieldinfo=c_fieldinfo)
  580. def by_name(self, name):
  581. c_fieldinfo = libvect.Vect_get_field_by_name(self.c_mapinfo, name)
  582. return Link(c_fieldinfo=c_fieldinfo)
  583. def num_dblinks(self):
  584. return libvect.Vect_get_num_dblinks(self.c_mapinfo)
  585. def add(self, link):
  586. """Add a new link. ::
  587. >>> from pygrass.vector import VectorTopo
  588. >>> municip = VectorTopo('boundary_municp_sqlite')
  589. >>> municip.open()
  590. >>> dblinks = DBlinks(municip.c_mapinfo)
  591. >>> dblinks
  592. DBlinks([Link(1, boundary_municp, sqlite)])
  593. >>> link = Link(2, 'pg_link', 'boundary_municp_pg', 'cat',
  594. ... 'host=localhost dbname=grassdb', 'pg')
  595. >>> dblinks.add(link)
  596. >>> dblinks # need to open vector map in write mode
  597. DBlinks([Link(1, boundary_municp, sqlite)])
  598. ..
  599. """
  600. #TODO: check if open in write mode or not.
  601. libvect.Vect_map_add_dblink(self.c_mapinfo,
  602. link.layer, link.name, link.table_name,
  603. link.key, link.database, link.driver)
  604. def remove(self, key):
  605. """Remove a link. ::
  606. >>> from pygrass.vector import VectorTopo
  607. >>> municip = VectorTopo('boundary_municp_sqlite')
  608. >>> municip.open()
  609. >>> dblinks = DBlinks(municip.c_mapinfo)
  610. >>> dblinks
  611. DBlinks([Link(1, boundary_municp, sqlite)])
  612. >>> dblinks.remove('pg_link')
  613. >>> dblinks # need to open vector map in write mode
  614. DBlinks([Link(1, boundary_municp, sqlite)])
  615. ..
  616. """
  617. if isinstance(key, str):
  618. key = self.from_name_to_num(key)
  619. libvect.Vect_map_del_dblink(self.c_mapinfo, key)
  620. def from_name_to_num(self, name):
  621. """
  622. Vect_get_field_number
  623. """
  624. return libvect.Vect_get_field_number(self.c_mapinfo, name)
  625. class Table(object):
  626. """::
  627. >>> import sqlite3
  628. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  629. >>> tab_sqlite = Table(name='boundary_municp_sqlite',
  630. ... connection=sqlite3.connect(get_path(path)))
  631. >>> tab_sqlite.name
  632. 'boundary_municp_sqlite'
  633. >>> import psycopg2
  634. >>> tab_pg = Table('boundary_municp_pg',
  635. ... psycopg2.connect('host=localhost dbname=grassdb',
  636. ... 'pg'))
  637. >>> tab_pg.columns # doctest: +ELLIPSIS
  638. Columns([('cat', 'int4'), ...])
  639. ..
  640. """
  641. def _get_name(self):
  642. return self._name
  643. def _set_name(self, new_name):
  644. old_name = self._name
  645. cur = self.conn.cursor()
  646. cur.execute(sql.RENAME_TAB.format(old_name=old_name,
  647. new_name=new_name))
  648. cur.commit()
  649. cur.close()
  650. name = property(fget=_get_name, fset=_set_name)
  651. def __init__(self, name, connection, key='cat'):
  652. self._name = name
  653. self.conn = connection
  654. self.key = key
  655. self.columns = Columns(self.name,
  656. self.conn,
  657. self.key)
  658. self.filters = Filters(self.name)
  659. def __repr__(self):
  660. """::
  661. >>> import sqlite3
  662. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  663. >>> tab_sqlite = Table(name='boundary_municp_sqlite',
  664. ... connection=sqlite3.connect(get_path(path)))
  665. >>> tab_sqlite
  666. Table('boundary_municp_sqlite')
  667. ..
  668. """
  669. return "Table(%r)" % (self.name)
  670. def __iter__(self):
  671. cur = self.execute()
  672. return (cur.fetchone() for _ in xrange(self.__len__()))
  673. def __len__(self):
  674. """Return the nuber of rows"""
  675. return self.num_rows()
  676. def num_rows(self):
  677. cur = self.conn.cursor()
  678. cur.execute(sql.SELECT.format(cols='Count(*)', tname=self.name))
  679. number = cur.fetchone()[0]
  680. cur.close()
  681. return number
  682. def execute(self, sql_code=None):
  683. """Execute SQL code from a given string or build with filters and
  684. return a cursor object. ::
  685. >>> import sqlite3
  686. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  687. >>> tab_sqlite = Table(name='boundary_municp_sqlite',
  688. ... connection=sqlite3.connect(get_path(path)))
  689. >>> tab_sqlite.filters.select('cat', 'COUNTY').order_by('AREA')
  690. Filters('SELECT cat, COUNTY FROM boundary_municp_sqlite ORDER BY AREA;')
  691. >>> cur = tab_sqlite.execute()
  692. >>> cur.fetchone()
  693. (1, u'SURRY')
  694. ..
  695. """
  696. try:
  697. sqlc = sql_code if sql_code else self.filters.get_sql()
  698. cur = self.conn.cursor()
  699. return cur.execute(sqlc)
  700. except:
  701. raise ValueError("The SQL is not correct:\n%r" % sqlc)
  702. def insert(self, values):
  703. cur = self.conn.cursor()
  704. return cur.execute(self.columns.insert_str, values)