table.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  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. def sql_descr(self, remove=None):
  169. """Return a string with description of columns.
  170. Remove it is used to remove a columns.::
  171. >>> import sqlite3
  172. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  173. >>> cols_sqlite = Columns('boundary_municp_sqlite',
  174. ... sqlite3.connect(get_path(path)))
  175. >>> cols_sqlite.sql_descr() # doctest: +ELLIPSIS
  176. u'cat integer, OBJECTID integer, AREA double precision, ...'
  177. >>> import psycopg2 as pg
  178. >>> cols_pg = Columns('boundary_municp_pg',
  179. ... pg.connect('host=localhost dbname=grassdb'))
  180. >>> cols_pg.sql_descr() # doctest: +ELLIPSIS
  181. 'cat int4, objectid int4, area float8, perimeter float8, ...'
  182. """
  183. if remove:
  184. return ', '.join(['%s %s' % (key, val) for key, val in self.items()
  185. if key != remove])
  186. else:
  187. return ', '.join(['%s %s' % (key, val)
  188. for key, val in self.items()])
  189. def types(self):
  190. """Return a list with the column types. ::
  191. >>> import sqlite3
  192. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  193. >>> cols_sqlite = Columns('boundary_municp_sqlite',
  194. ... sqlite3.connect(get_path(path)))
  195. >>> cols_sqlite.types() # doctest: +ELLIPSIS
  196. [u'integer', u'integer', ...]
  197. >>> import psycopg2 as pg
  198. >>> cols_pg = Columns('boundary_municp_pg',
  199. ... pg.connect('host=localhost dbname=grassdb'))
  200. >>> cols_pg.types() # doctest: +ELLIPSIS
  201. ['int4', 'int4', 'float8', 'float8', 'float8', ...]
  202. ..
  203. """
  204. return self.odict.values()
  205. def names(self, remove=None, unicod=True):
  206. """Return a list with the column names.
  207. Remove it is used to remove a columns.::
  208. >>> import sqlite3
  209. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  210. >>> cols_sqlite = Columns('boundary_municp_sqlite',
  211. ... sqlite3.connect(get_path(path)))
  212. >>> cols_sqlite.names() # doctest: +ELLIPSIS
  213. [u'cat', u'OBJECTID', u'AREA', u'PERIMETER', ...]
  214. >>> import psycopg2 as pg
  215. >>> cols_pg = Columns('boundary_municp_pg',
  216. ... pg.connect('host=localhost dbname=grassdb'))
  217. >>> cols_pg.names() # doctest: +ELLIPSIS
  218. ['cat', 'objectid', 'area', 'perimeter', ...]
  219. ..
  220. """
  221. if remove:
  222. nams = self.odict.keys()
  223. nams.remove(remove)
  224. else:
  225. nams = self.odict.keys()
  226. if unicod:
  227. return nams
  228. else:
  229. return [str(name) for name in nams]
  230. def items(self):
  231. """Return a list of tuple with column name and column type. ::
  232. >>> import sqlite3
  233. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  234. >>> cols_sqlite = Columns('boundary_municp_sqlite',
  235. ... sqlite3.connect(get_path(path)))
  236. >>> cols_sqlite.items() # doctest: +ELLIPSIS
  237. [(u'cat', u'integer'), ...]
  238. >>> import psycopg2 as pg
  239. >>> cols_pg = Columns('boundary_municp_pg',
  240. ... pg.connect('host=localhost dbname=grassdb'))
  241. >>> cols_pg.items() # doctest: +ELLIPSIS
  242. [('cat', 'int4'), ('objectid', 'int4'), ('area', 'float8'), ...]
  243. ..
  244. """
  245. return self.odict.items()
  246. def add(self, col_name, col_type):
  247. """Add a new column to the table. ::
  248. >>> import sqlite3
  249. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  250. >>> cols_sqlite = Columns('boundary_municp_sqlite',
  251. ... sqlite3.connect(get_path(path)))
  252. >>> cols_sqlite.add('n_pizza', 'int4')
  253. >>> 'n_pizza' in cols_sqlite
  254. True
  255. >>> import psycopg2 as pg
  256. >>> cols_pg = Columns('boundary_municp_pg',
  257. ... pg.connect('host=localhost dbname=grassdb'))
  258. >>> cols_pg.add('n_pizza', 'int4')
  259. >>> 'n_pizza' in cols_pg
  260. True
  261. ..
  262. """
  263. cur = self.conn.cursor()
  264. cur.execute(sql.ADD_COL.format(tname=self.tname,
  265. cname=col_name,
  266. ctype=col_type))
  267. self.conn.commit()
  268. cur.close()
  269. self.update_odict()
  270. def rename(self, old_name, new_name):
  271. """Rename a column of the table. ::
  272. >>> import sqlite3
  273. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  274. >>> cols_sqlite = Columns('boundary_municp_sqlite',
  275. ... sqlite3.connect(get_path(path)))
  276. >>> cols_sqlite.rename('n_pizza', 'n_pizzas') # doctest: +ELLIPSIS
  277. >>> 'n_pizza' in cols_sqlite
  278. False
  279. >>> 'n_pizzas' in cols_sqlite
  280. True
  281. >>> import psycopg2 as pg
  282. >>> cols_pg = Columns('boundary_municp_pg',
  283. ... pg.connect('host=localhost dbname=grassdb'))
  284. >>> cols_pg.rename('n_pizza', 'n_pizzas')
  285. >>> 'n_pizza' in cols_pg
  286. False
  287. >>> 'n_pizzas' in cols_pg
  288. True
  289. ..
  290. """
  291. cur = self.conn.cursor()
  292. if self.is_pg():
  293. cur.execute(sql.RENAME_COL.format(tname=self.tname,
  294. old_name=old_name,
  295. new_name=new_name))
  296. self.conn.commit()
  297. cur.close()
  298. self.update_odict()
  299. else:
  300. cur.execute(sql.ADD_COL.format(tname=self.tname,
  301. cname=new_name,
  302. ctype=str(self.odict[old_name])))
  303. cur.execute(sql.UPDATE.format(tname=self.tname,
  304. new_col=new_name,
  305. old_col=old_name))
  306. self.conn.commit()
  307. cur.close()
  308. self.update_odict()
  309. self.drop(old_name)
  310. def cast(self, col_name, new_type):
  311. """Change the column type. ::
  312. >>> import sqlite3
  313. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  314. >>> cols_sqlite = Columns('boundary_municp_sqlite',
  315. ... sqlite3.connect(get_path(path)))
  316. >>> cols_sqlite.cast('n_pizzas', 'float8') # doctest: +ELLIPSIS
  317. Traceback (most recent call last):
  318. ...
  319. DBError: 'SQLite does not support to cast columns.'
  320. >>> import psycopg2 as pg
  321. >>> cols_pg = Columns('boundary_municp_pg',
  322. ... pg.connect('host=localhost dbname=grassdb'))
  323. >>> cols_pg.cast('n_pizzas', 'float8')
  324. >>> cols_pg['n_pizzas']
  325. 'float8'
  326. .. warning ::
  327. It is not possible to cast a column with sqlite
  328. ..
  329. """
  330. if self.is_pg():
  331. cur = self.conn.cursor()
  332. cur.execute(sql.CAST_COL.format(tname=self.tname, col=col_name,
  333. ctype=new_type))
  334. self.conn.commit()
  335. cur.close()
  336. self.update_odict()
  337. else:
  338. # sqlite does not support rename columns:
  339. raise DBError('SQLite does not support to cast columns.')
  340. def drop(self, col_name):
  341. """Drop a column from the table. ::
  342. >>> import sqlite3
  343. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  344. >>> cols_sqlite = Columns('boundary_municp_sqlite',
  345. ... sqlite3.connect(get_path(path)))
  346. >>> cols_sqlite.drop('n_pizzas') # doctest: +ELLIPSIS
  347. >>> 'n_pizzas' in cols_sqlite
  348. False
  349. >>> import psycopg2 as pg
  350. >>> cols_pg = Columns('boundary_municp_pg',
  351. ... pg.connect('host=localhost dbname=grassdb'))
  352. >>> cols_pg.drop('n_pizzas')
  353. >>> 'n_pizzas' in cols_pg
  354. False
  355. ..
  356. """
  357. cur = self.conn.cursor()
  358. if self.is_pg():
  359. cur.execute(sql.DROP_COL.format(tname=self.tname,
  360. cname=col_name))
  361. else:
  362. desc = str(self.sql_descr(remove=col_name))
  363. names = ', '.join(self.names(remove=col_name, unicod=False))
  364. queries = sql.DROP_COL_SQLITE.format(tname=self.tname,
  365. keycol=self.key,
  366. coldef=desc,
  367. colnames=names).split('\n')
  368. for query in queries:
  369. cur.execute(query)
  370. self.conn.commit()
  371. cur.close()
  372. self.update_odict()
  373. class Link(object):
  374. """Define a Link between vector map and the attributes table.
  375. It is possible to define a Link object or given all the information
  376. (number, name, table name, key, database, driver): ::
  377. >>> link = Link(1, 'link0', 'boundary_municp_sqlite', 'cat',
  378. ... '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db', 'sqlite')
  379. >>> link.number
  380. 1
  381. >>> link.name
  382. 'link0'
  383. >>> link.table_name
  384. 'boundary_municp_sqlite'
  385. >>> link.key
  386. 'cat'
  387. >>> link.database
  388. '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  389. >>> link.driver
  390. 'sqlite'
  391. >>> link
  392. Link(1, link0, sqlite)
  393. It is possible to change parameters with: ::
  394. >>> link.driver = 'pg'
  395. >>> link.driver
  396. 'pg'
  397. >>> link.driver = 'postgres' # doctest: +ELLIPSIS
  398. Traceback (most recent call last):
  399. ...
  400. TypeError: Driver not supported, use: sqlite, pg.
  401. >>> link.driver
  402. 'pg'
  403. >>> link.number = 0 # doctest: +ELLIPSIS
  404. Traceback (most recent call last):
  405. ...
  406. TypeError: Number must be positive and greater than 0.
  407. Or given a c_fieldinfo object that is a ctypes pointer to the field_info C
  408. struct. ::
  409. >>> link = Link(c_fieldinfo = ctypes.pointer(libvect.field_info()))
  410. ..
  411. """
  412. def _get_number(self):
  413. return self.c_fieldinfo.contents.number
  414. def _set_number(self, number):
  415. if number <= 0:
  416. raise TypeError("Number must be positive and greater than 0.")
  417. self.c_fieldinfo.contents.number = number
  418. number = property(fget=_get_number, fset=_set_number)
  419. def _get_name(self):
  420. return self.c_fieldinfo.contents.name
  421. def _set_name(self, name):
  422. self.c_fieldinfo.contents.name = name
  423. name = property(fget=_get_name, fset=_set_name)
  424. def _get_table(self):
  425. return self.c_fieldinfo.contents.table
  426. def _set_table(self, new_name):
  427. self.c_fieldinfo.contents.table = new_name
  428. table_name = property(fget=_get_table, fset=_set_table)
  429. def _get_key(self):
  430. return self.c_fieldinfo.contents.key
  431. def _set_key(self, key):
  432. self.c_fieldinfo.contents.key = key
  433. key = property(fget=_get_key, fset=_set_key)
  434. def _get_database(self):
  435. return self.c_fieldinfo.contents.database
  436. def _set_database(self, database):
  437. self.c_fieldinfo.contents.database = database
  438. database = property(fget=_get_database, fset=_set_database)
  439. def _get_driver(self):
  440. return self.c_fieldinfo.contents.driver
  441. def _set_driver(self, driver):
  442. if driver not in ('sqlite', 'pg'):
  443. str_err = "Driver not supported, use: %s." % ", ".join(DRIVERS)
  444. raise TypeError(str_err)
  445. self.c_fieldinfo.contents.driver = driver
  446. driver = property(fget=_get_driver, fset=_set_driver)
  447. def __init__(self, number=None, name=None, table=None, key=None,
  448. database=None, driver=None, c_fieldinfo=None):
  449. if c_fieldinfo is not None:
  450. self.c_fieldinfo = c_fieldinfo
  451. else:
  452. self.c_fieldinfo = ctypes.pointer(libvect.field_info())
  453. self.number = number
  454. self.name = name
  455. self.table_name = table
  456. self.key = key
  457. self.database = database
  458. self.driver = driver
  459. def __repr__(self):
  460. return "Link(%d, %s, %s)" % (self.number, self.name, self.driver)
  461. def connection(self):
  462. """Return a connection object. ::
  463. >>> link = Link(1, 'link0', 'boundary_municp_sqlite', 'cat',
  464. ... '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db',
  465. ... 'sqlite')
  466. >>> conn = link.connection()
  467. >>> cur = conn.cursor()
  468. >>> cur.execute("SELECT cat,COUNTY,PERIMETER FROM %s" %
  469. ... link.table_name) # doctest: +ELLIPSIS
  470. <sqlite3.Cursor object at ...>
  471. >>> cur.fetchone()
  472. (1, u'SURRY', 1415.331)
  473. >>> cur.close()
  474. >>> conn.close()
  475. ...
  476. """
  477. if self.driver == 'sqlite':
  478. import sqlite3
  479. return sqlite3.connect(get_path(self.database))
  480. elif self.driver == 'pg':
  481. try:
  482. import psycopg2
  483. db = ' '.join(self.database.split(','))
  484. return psycopg2.connect(db)
  485. except ImportError:
  486. er = "You need to install psycopg2 to connect with this table."
  487. raise ImportError(er)
  488. else:
  489. str_err = "Driver is not supported yet, pleas use: sqlite or pg"
  490. raise TypeError(str_err)
  491. def table(self):
  492. """Return a Table object. ::
  493. >>> link = Link(1, 'link0', 'boundary_municp_sqlite', 'cat',
  494. ... '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db',
  495. ... 'sqlite')
  496. >>> table = link.table()
  497. >>> table.filters.select('cat', 'COUNTY', 'PERIMETER')
  498. Filters('SELECT cat, COUNTY, PERIMETER FROM boundary_municp_sqlite;')
  499. >>> cur = table.execute()
  500. >>> cur.fetchone()
  501. (1, u'SURRY', 1415.331)
  502. >>> cur.close()
  503. ..
  504. """
  505. return Table(self.table_name, self.connection(), self.key)
  506. def info(self):
  507. """Print information of the link. ::
  508. >>> link = Link(1, 'link0', 'boundary_municp_sqlite', 'cat',
  509. ... '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db',
  510. ... 'sqlite')
  511. >>> link.info()
  512. number: 1
  513. name: link0
  514. table: boundary_municp_sqlite
  515. key: cat
  516. database: $GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db
  517. driver: sqlite
  518. ..
  519. """
  520. print "number: ", self.number
  521. print "name: ", self.name
  522. print "table: ", self.table_name
  523. print "key: ", self.key
  524. print "database: ", self.database
  525. print "driver: ", self.driver
  526. class DBlinks(object):
  527. """Interface containing link to the table DB. ::
  528. >>> from pygrass.vector import VectorTopo
  529. >>> municip = VectorTopo('boundary_municp_sqlite')
  530. >>> municip.open()
  531. >>> dblinks = DBlinks(municip.c_mapinfo)
  532. >>> dblinks
  533. DBlinks([Link(1, boundary_municp, sqlite)])
  534. >>> dblinks[1]
  535. Link(1, boundary_municp, sqlite)
  536. >>> dblinks[0] # doctest: +ELLIPSIS
  537. Traceback (most recent call last):
  538. ...
  539. TypeError: The index must be != 0.
  540. >>> dblinks['boundary_municp']
  541. Link(1, boundary_municp, sqlite)
  542. ..
  543. """
  544. def __init__(self, c_mapinfo):
  545. self.c_mapinfo = c_mapinfo
  546. def __len__(self):
  547. return self.num_dblinks()
  548. def __iter__(self):
  549. return (self.by_number(ilink)
  550. for ilink in xrange(1, self.num_dblinks() + 1))
  551. def __getitem__(self, key):
  552. """
  553. """
  554. if isinstance(key, int):
  555. if key != 0:
  556. return self.by_number(key)
  557. else:
  558. raise TypeError("The index must be != 0.")
  559. else:
  560. return self.by_name(key)
  561. def __repr__(self):
  562. return "DBlinks(%r)" % [link for link in self.__iter__()]
  563. def by_number(self, number):
  564. c_fieldinfo = libvect.Vect_get_field(self.c_mapinfo, number)
  565. return Link(c_fieldinfo=c_fieldinfo)
  566. def by_name(self, name):
  567. c_fieldinfo = libvect.Vect_get_field_by_name(self.c_mapinfo, name)
  568. return Link(c_fieldinfo=c_fieldinfo)
  569. def num_dblinks(self):
  570. return libvect.Vect_get_num_dblinks(self.c_mapinfo)
  571. def add(self, link):
  572. """Add a new link. ::
  573. >>> from pygrass.vector import VectorTopo
  574. >>> municip = VectorTopo('boundary_municp_sqlite')
  575. >>> municip.open()
  576. >>> dblinks = DBlinks(municip.c_mapinfo)
  577. >>> dblinks
  578. DBlinks([Link(1, boundary_municp, sqlite)])
  579. >>> link = Link(2, 'pg_link', 'boundary_municp_pg', 'cat',
  580. ... 'host=localhost dbname=grassdb', 'pg')
  581. >>> dblinks.add(link)
  582. >>> dblinks # need to open vector map in write mode
  583. DBlinks([Link(1, boundary_municp, sqlite)])
  584. ..
  585. """
  586. #TODO: check if open in write mode or not.
  587. libvect.Vect_map_add_dblink(self.c_mapinfo,
  588. link.number, link.name, link.table_name,
  589. link.key, link.database, link.driver)
  590. def remove(self, key):
  591. """Remove a link. ::
  592. >>> from pygrass.vector import VectorTopo
  593. >>> municip = VectorTopo('boundary_municp_sqlite')
  594. >>> municip.open()
  595. >>> dblinks = DBlinks(municip.c_mapinfo)
  596. >>> dblinks
  597. DBlinks([Link(1, boundary_municp, sqlite)])
  598. >>> dblinks.remove('pg_link')
  599. >>> dblinks # need to open vector map in write mode
  600. DBlinks([Link(1, boundary_municp, sqlite)])
  601. ..
  602. """
  603. if isinstance(key, str):
  604. key = self.from_name_to_num(key)
  605. libvect.Vect_map_del_dblink(self.c_mapinfo, key)
  606. def from_name_to_num(self, name):
  607. """
  608. Vect_get_field_number
  609. """
  610. return libvect.Vect_get_field_number(self.c_mapinfo, name)
  611. class Table(object):
  612. """::
  613. >>> import sqlite3
  614. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  615. >>> tab_sqlite = Table(name='boundary_municp_sqlite',
  616. ... connection=sqlite3.connect(get_path(path)))
  617. >>> tab_sqlite.name
  618. 'boundary_municp_sqlite'
  619. >>> import psycopg2
  620. >>> tab_pg = Table('boundary_municp_pg',
  621. ... psycopg2.connect('host=localhost dbname=grassdb',
  622. ... 'pg'))
  623. >>> tab_pg.columns # doctest: +ELLIPSIS
  624. Columns([('cat', 'int4'), ...])
  625. ..
  626. """
  627. def _get_name(self):
  628. return self._name
  629. def _set_name(self, new_name):
  630. old_name = self._name
  631. cur = self.conn.cursor()
  632. cur.execute(sql.RENAME_TAB.format(old_name=old_name,
  633. new_name=new_name))
  634. cur.commit()
  635. cur.close()
  636. name = property(fget=_get_name, fset=_set_name)
  637. def __init__(self, name, connection, key='cat'):
  638. self._name = name
  639. self.conn = connection
  640. self.key = key
  641. self.columns = Columns(self.name,
  642. self.conn,
  643. self.key)
  644. self.filters = Filters(self.name)
  645. def __repr__(self):
  646. """::
  647. >>> import sqlite3
  648. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  649. >>> tab_sqlite = Table(name='boundary_municp_sqlite',
  650. ... connection=sqlite3.connect(get_path(path)))
  651. >>> tab_sqlite
  652. Table('boundary_municp_sqlite')
  653. ..
  654. """
  655. return "Table(%r)" % (self.name)
  656. def __iter__(self):
  657. cur = self.execute()
  658. return (cur.fetchone() for _ in xrange(self.__len__()))
  659. def __len__(self):
  660. """Return the nuber of rows"""
  661. return self.num_rows()
  662. def num_rows(self):
  663. cur = self.conn.cursor()
  664. cur.execute(sql.SELECT.format(cols='Count(*)', tname=self.name))
  665. number = cur.fetchone()[0]
  666. cur.close()
  667. return number
  668. def execute(self, sql_code=None):
  669. """Execute SQL code from a given string or build with filters and
  670. return a cursor object. ::
  671. >>> import sqlite3
  672. >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db'
  673. >>> tab_sqlite = Table(name='boundary_municp_sqlite',
  674. ... connection=sqlite3.connect(get_path(path)))
  675. >>> tab_sqlite.filters.select('cat', 'COUNTY').order_by('AREA')
  676. Filters('SELECT cat, COUNTY FROM boundary_municp_sqlite ORDER BY AREA;')
  677. >>> cur = tab_sqlite.execute()
  678. >>> cur.fetchone()
  679. (1, u'SURRY')
  680. ..
  681. """
  682. if sql_code is not None:
  683. cur = self.conn.cursor()
  684. return cur.execute(sql_code)
  685. # get the sql from filters
  686. sql_code = self.filters.get_sql()
  687. if sql_code is not None:
  688. cur = self.conn.cursor()
  689. return cur.execute(sql_code)