table.py 28 KB

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