sqlite.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. #============================================================================
  2. # This file is part of Pwman3.
  3. #
  4. # Pwman3 is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License, version 2
  6. # as published by the Free Software Foundation;
  7. #
  8. # Pwman3 is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with Pwman3; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  16. #============================================================================
  17. # Copyright (C) 2012 Oz Nahum <nahumoz@gmail.com>
  18. #============================================================================
  19. #============================================================================
  20. # Copyright (C) 2006 Ivan Kelly <ivan@ivankelly.net>
  21. #============================================================================
  22. """SQLite Database implementation."""
  23. from pwman.data.database import Database, DatabaseException
  24. from pwman.data.nodes import Node
  25. from pwman.data.nodes import NewNode
  26. from pwman.data.tags import Tag
  27. import sys
  28. if sys.version_info > (2, 5):
  29. import sqlite3 as sqlite
  30. else:
  31. try:
  32. from pysqlite2 import dbapi2 as sqlite
  33. except ImportError:
  34. raise DatabaseException("python-sqlite2 not installed")
  35. import pwman.util.config as config
  36. import cPickle
  37. def check_db_version():
  38. """
  39. check the data base version query the right table
  40. """
  41. try:
  42. filename = config.get_value('Database', 'filename')
  43. con = sqlite.connect(filename)
  44. cur = con.cursor()
  45. cur.execute("PRAGMA TABLE_INFO(DBVERSION)")
  46. row = cur.fetchone()
  47. if row is None:
  48. return "0.3"
  49. try:
  50. return row[-2]
  51. except IndexError:
  52. raise DatabaseException("Something seems fishy with the DB")
  53. except sqlite.DatabaseError, e:
  54. raise DatabaseException("SQLite: %s" % (e))
  55. class SQLiteDatabaseNewForm(Database):
  56. """SQLite Database implementation"""
  57. def __init__(self, filename=None):
  58. """Initialise SQLitePwmanDatabase instance."""
  59. Database.__init__(self)
  60. if filename:
  61. self._filename = filename
  62. else:
  63. try:
  64. self._filename = config.get_value('Database', 'filename')
  65. except KeyError, e:
  66. raise DatabaseException(
  67. "SQLite: missing parameter [%s]" % (e))
  68. def _open(self):
  69. try:
  70. self._con = sqlite.connect(self._filename)
  71. self._cur = self._con.cursor()
  72. self._checktables()
  73. except sqlite.DatabaseError, e:
  74. raise DatabaseException("SQLite: %s" % (e))
  75. def close(self):
  76. self._cur.close()
  77. self._con.close()
  78. def listtags(self, alltags=False):
  79. sql = ''
  80. params = []
  81. if not self._filtertags or alltags:
  82. sql = "SELECT DATA FROM TAGS ORDER BY DATA ASC"
  83. else:
  84. sql = ("SELECT TAGS.DATA FROM LOOKUP"
  85. + " INNER JOIN TAGS ON LOOKUP.TAG = TAGS.ID"
  86. + " WHERE NODE IN (")
  87. first = True
  88. for t in self._filtertags:
  89. if not first:
  90. sql += " INTERSECT "
  91. else:
  92. first = False
  93. sql += ("SELECT NODE FROM LOOKUP LEFT JOIN TAGS ON TAG = "
  94. + " TAGS.ID WHERE TAGS.DATA = ?")
  95. params.append(t._name)
  96. sql += ") EXCEPT SELECT DATA FROM TAGS WHERE "
  97. first = True
  98. for t in self._filtertags:
  99. if not first:
  100. sql += " OR "
  101. else:
  102. first = False
  103. sql += "TAGS.DATA = ?"
  104. params.append(t._name)
  105. try:
  106. self._cur.execute(sql, params)
  107. tags = []
  108. row = self._cur.fetchone()
  109. while row is not None:
  110. tagstring = str(row[0])
  111. tags.append(tagstring)
  112. row = self._cur.fetchone()
  113. return tags
  114. except sqlite.DatabaseError, e:
  115. raise DatabaseException("SQLite: %s" % (e))
  116. except sqlite.InterfaceError, e:
  117. import ipdb
  118. ipdb.set_trace() # XXX BREAKPOINT
  119. def parse_node_string(self, string):
  120. nodestring = string.split("##")
  121. keyvals = {}
  122. for pair in nodestring[:-1]:
  123. key, val = pair.split(":")
  124. keyvals[key.lstrip('##')] = val
  125. tags = nodestring[-1]
  126. tags = tags.split("tags:", 1)[1]
  127. tags = tags.split("tag:")
  128. tags = [tag.split('**endtag**')[0] for tag in tags]
  129. return keyvals, tags
  130. def getnodes(self, ids):
  131. """
  132. object should always be: (ipwman.data.nodes
  133. """
  134. nodes = []
  135. for i in ids:
  136. sql = "SELECT DATA FROM NODES WHERE ID = ?"
  137. self._cur.execute(sql, [i])
  138. row = self._cur.fetchone()
  139. if row is not None:
  140. nodestring = str(row[0])
  141. nodeargs, tags = self.parse_node_string(nodestring)
  142. node = NewNode(**nodeargs)
  143. node.tags = tags
  144. node._id = i
  145. nodes.append(node)
  146. return nodes
  147. def editnode(self, id, node):
  148. try:
  149. sql = "UPDATE NODES SET DATA = ? WHERE ID = ?"
  150. self._cur.execute(sql, [node.dump_edit_to_db()[0], id])
  151. except sqlite.DatabaseError, e:
  152. raise DatabaseException("SQLite: %s" % (e))
  153. self._setnodetags(node)
  154. self._checktags()
  155. self._commit()
  156. def addnodes(self, nodes):
  157. """
  158. This method writes the data as an ecrypted string to
  159. the database
  160. """
  161. for n in nodes:
  162. sql = "INSERT INTO NODES(DATA) VALUES(?)"
  163. value = n.dump_to_db()
  164. try:
  165. self._cur.execute(sql, value)
  166. except sqlite.DatabaseError, e:
  167. raise DatabaseException("SQLite: %s" % (e))
  168. idx = self._cur.lastrowid
  169. n._id = idx
  170. self._setnodetags(n)
  171. self._commit()
  172. def removenodes(self, nodes):
  173. for n in nodes:
  174. # if not isinstance(n, Node): raise DatabaseException(
  175. # "Tried to delete foreign object from database [%s]", n)
  176. try:
  177. sql = "DELETE FROM NODES WHERE ID = ?"
  178. self._cur.execute(sql, [n._id])
  179. except sqlite.DatabaseError, e:
  180. raise DatabaseException("SQLite: %s" % (e))
  181. self._deletenodetags(n)
  182. self._checktags()
  183. self._commit()
  184. def listnodes(self):
  185. sql = ''
  186. params = []
  187. if len(self._filtertags) == 0:
  188. sql = "SELECT ID FROM NODES ORDER BY ID ASC"
  189. else:
  190. first = True
  191. for t in self._filtertags:
  192. if not first:
  193. sql += " INTERSECT "
  194. else:
  195. first = False
  196. sql += ("SELECT NODE FROM LOOKUP LEFT JOIN TAGS ON TAG = "
  197. " TAGS.ID WHERE TAGS.DATA = ? ")
  198. params = [t.name.strip()]
  199. try:
  200. self._cur.execute(sql, params)
  201. rows = self._cur.fetchall()
  202. ids = [row[0] for row in rows]
  203. return ids
  204. except sqlite.DatabaseError, e:
  205. raise DatabaseException("SQLite: %s" % (e))
  206. def _commit(self):
  207. try:
  208. self._con.commit()
  209. except sqlite.DatabaseError, e:
  210. self._con.rollback()
  211. raise DatabaseException(
  212. "SQLite: Error commiting data to db [%s]" % (e))
  213. def _create_tag(self, tag, node_ids):
  214. """add tags to db"""
  215. sql = "INSERT OR REPLACE INTO TAGS(DATA) VALUES(?)"
  216. if isinstance(tag, str):
  217. self._cur.execute(sql, [tag])
  218. else:
  219. self._cur.execute(sql, [tag._name])
  220. def _update_tag_lookup(self, node, tag_id):
  221. sql = "INSERT OR REPLACE INTO LOOKUP VALUES(?, ?)"
  222. params = [node._id, tag_id]
  223. try:
  224. self._cur.execute(sql, params)
  225. except sqlite.DatabaseError, e:
  226. raise DatabaseException("SQLite: %s" % (e))
  227. def _tagids(self, tags):
  228. ids = []
  229. sql = "SELECT ID FROM TAGS WHERE DATA = ?"
  230. for tag in tags:
  231. try:
  232. if isinstance(tag, str):
  233. self._cur.execute(sql, [tag])
  234. else:
  235. self._cur.execute(sql, [tag._name])
  236. row = self._cur.fetchone()
  237. if (row is not None):
  238. ids.append(row[0])
  239. else:
  240. self._create_tag(tag, None)
  241. ids.append(self._cur.lastrowid)
  242. except sqlite.DatabaseError, e:
  243. raise DatabaseException("SQLite: %s" % (e))
  244. return ids
  245. def _deletenodetags(self, node):
  246. try:
  247. sql = "DELETE FROM LOOKUP WHERE NODE = ?"
  248. self._cur.execute(sql, [node._id])
  249. except sqlite.DatabaseError, e:
  250. raise DatabaseException("SQLite: %s" % (e))
  251. self._commit()
  252. def _setnodetags(self, node):
  253. self._deletenodetags(node)
  254. ids = self._tagids(node.tags)
  255. for tagid in ids:
  256. self._update_tag_lookup(node, tagid)
  257. self._commit()
  258. def _checktags(self):
  259. try:
  260. sql = "DELETE FROM TAGS WHERE ID NOT IN (SELECT TAG FROM" \
  261. + " LOOKUP GROUP BY TAG)"
  262. self._cur.execute(sql)
  263. except sqlite.DatabaseError, e:
  264. raise DatabaseException("SQLite: %s" % (e))
  265. self._commit()
  266. def _checktables(self):
  267. """
  268. Check if the Pwman tables exist.
  269. TODO: This method should check the version of the
  270. database. If it finds an old format it should
  271. exis, and prompt the user to convert the database
  272. to the new version with a designated script.
  273. """
  274. self._cur.execute("PRAGMA TABLE_INFO(NODES)")
  275. if (self._cur.fetchone() is None):
  276. # table doesn't exist, create it
  277. # SQLite does have constraints implemented at the moment
  278. # so datatype will just be a string
  279. self._cur.execute("CREATE TABLE NODES (ID INTEGER PRIMARY KEY"
  280. + " AUTOINCREMENT,DATA BLOB NOT NULL)")
  281. self._cur.execute("CREATE TABLE TAGS"
  282. + "(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
  283. + "DATA BLOB NOT NULL UNIQUE)")
  284. self._cur.execute("CREATE TABLE LOOKUP"
  285. + "(NODE INTEGER NOT NULL, TAG INTEGER NOT NULL,"
  286. + " PRIMARY KEY(NODE, TAG))")
  287. self._cur.execute("CREATE TABLE KEY"
  288. + "(THEKEY TEXT NOT NULL DEFAULT '')")
  289. self._cur.execute("INSERT INTO KEY VALUES('')")
  290. # create a table to hold DB version info
  291. self._cur.execute("CREATE TABLE DBVERSION"
  292. + "(DBVERSION TEXT NOT NULL DEFAULT '0.4')")
  293. self._cur.execute("INSERT INTO DBVERSION VALUES('0.4')")
  294. try:
  295. self._con.commit()
  296. except DatabaseException, e:
  297. self._con.rollback()
  298. raise e
  299. def savekey(self, key):
  300. """
  301. This function is saving the key to table KEY.
  302. The key already arrives as an encrypted string.
  303. It is the same self._keycrypted from
  304. crypto py (check with id(self._keycrypted) and
  305. id(key) here.
  306. """
  307. sql = "UPDATE KEY SET THEKEY = ?"
  308. values = [key]
  309. self._cur.execute(sql, values)
  310. try:
  311. self._con.commit()
  312. except sqlite.DatabaseError, e:
  313. self._con.rollback()
  314. raise DatabaseException(
  315. "SQLite: Error saving key [%s]" % (e))
  316. def loadkey(self):
  317. """
  318. fetch the key to database. the key is also stored
  319. encrypted.
  320. """
  321. self._cur.execute("SELECT THEKEY FROM KEY")
  322. keyrow = self._cur.fetchone()
  323. if (keyrow[0] == ''):
  324. return None
  325. else:
  326. return keyrow[0]
  327. class SQLiteDatabase(Database):
  328. """SQLite Database implementation"""
  329. def __init__(self):
  330. """Initialise SQLitePwmanDatabase instance."""
  331. Database.__init__(self)
  332. try:
  333. self._filename = config.get_value('Database', 'filename')
  334. except KeyError, e:
  335. raise DatabaseException(
  336. "SQLite: missing parameter [%s]" % (e))
  337. def _open(self):
  338. try:
  339. self._con = sqlite.connect(self._filename)
  340. self._cur = self._con.cursor()
  341. self._checktables()
  342. except sqlite.DatabaseError, e:
  343. raise DatabaseException("SQLite: %s" % (e))
  344. def close(self):
  345. self._cur.close()
  346. self._con.close()
  347. def listtags(self, alltags=False):
  348. sql = ''
  349. params = []
  350. if len(self._filtertags) == 0 or alltags:
  351. sql = "SELECT DATA FROM TAGS ORDER BY DATA ASC"
  352. else:
  353. sql = ("SELECT TAGS.DATA FROM LOOKUP"
  354. + " INNER JOIN TAGS ON LOOKUP.TAG = TAGS.ID"
  355. + " WHERE NODE IN (")
  356. first = True
  357. # if using the command filter, the code crashes ...
  358. #
  359. for t in self._filtertags:
  360. if not first:
  361. sql += " INTERSECT "
  362. else:
  363. first = False
  364. sql += ("SELECT NODE FROM LOOKUP LEFT JOIN TAGS ON TAG " +
  365. + " = TAGS.ID "
  366. + " WHERE TAGS.DATA = ?")
  367. params.append(cPickle.dumps(t))
  368. sql += ") EXCEPT SELECT DATA FROM TAGS WHERE "
  369. first = True
  370. for t in self._filtertags:
  371. if not first:
  372. sql += " OR "
  373. else:
  374. first = False
  375. sql += "TAGS.DATA = ?"
  376. params.append(t)
  377. try:
  378. print params
  379. self._cur.execute(sql, params)
  380. tags = []
  381. row = self._cur.fetchone()
  382. while (row is not None):
  383. tag = cPickle.loads(str(row[0]))
  384. tags.append(tag)
  385. row = self._cur.fetchone()
  386. return tags
  387. except sqlite.DatabaseError, e:
  388. raise DatabaseException("SQLite: %s" % (e))
  389. def getnodes(self, ids):
  390. nodes = []
  391. for i in ids:
  392. sql = "SELECT DATA FROM NODES WHERE ID = ?"
  393. try:
  394. self._cur.execute(sql, [i])
  395. row = self._cur.fetchone()
  396. if row is not None:
  397. node = cPickle.loads(str(row[0]))
  398. node.set_id(i)
  399. nodes.append(node)
  400. except sqlite.DatabaseError, e:
  401. raise DatabaseException("SQLite: %s" % (e))
  402. return nodes
  403. def editnode(self, id, node):
  404. if not isinstance(node, Node):
  405. raise DatabaseException(
  406. "Tried to insert foreign object into database [%s]" % node)
  407. try:
  408. sql = "UPDATE NODES SET DATA = ? WHERE ID = ?"
  409. self._cur.execute(sql, [cPickle.dumps(node), id])
  410. except sqlite.DatabaseError, e:
  411. raise DatabaseException("SQLite: %s" % (e))
  412. self._setnodetags(node)
  413. self._checktags()
  414. self._commit()
  415. def addnodes(self, nodes):
  416. for n in nodes:
  417. sql = "INSERT INTO NODES(DATA) VALUES(?)"
  418. if not isinstance(n, Node):
  419. raise DatabaseException(
  420. "Tried to insert foreign object into database [%s]", n)
  421. value = cPickle.dumps(n)
  422. try:
  423. self._cur.execute(sql, [value])
  424. except sqlite.DatabaseError, e:
  425. raise DatabaseException("SQLite: %s" % (e))
  426. id = self._cur.lastrowid
  427. n.set_id(id)
  428. self._setnodetags(n)
  429. self._commit()
  430. def removenodes(self, nodes):
  431. for n in nodes:
  432. if not isinstance(n, Node):
  433. raise DatabaseException(
  434. "Tried to delete foreign object from database [%s]", n)
  435. try:
  436. sql = "DELETE FROM NODES WHERE ID = ?"
  437. self._cur.execute(sql, [n.get_id()])
  438. except sqlite.DatabaseError, e:
  439. raise DatabaseException("SQLite: %s" % (e))
  440. self._deletenodetags(n)
  441. self._checktags()
  442. self._commit()
  443. def listnodes(self):
  444. sql = ''
  445. params = []
  446. if len(self._filtertags) == 0:
  447. sql = "SELECT ID FROM NODES ORDER BY ID ASC"
  448. else:
  449. first = True
  450. for t in self._filtertags:
  451. if not first:
  452. sql += " INTERSECT "
  453. else:
  454. first = False
  455. sql += ("SELECT NODE FROM LOOKUP LEFT JOIN TAGS "
  456. + " ON TAG = TAGS.ID"
  457. + " WHERE TAGS.DATA = ? ")
  458. params.append(cPickle.dumps(t))
  459. try:
  460. self._cur.execute(sql, params)
  461. ids = []
  462. row = self._cur.fetchone()
  463. while (row is not None):
  464. ids.append(row[0])
  465. row = self._cur.fetchone()
  466. return ids
  467. except sqlite.DatabaseError, e:
  468. raise DatabaseException("SQLite: %s" % (e))
  469. def _commit(self):
  470. try:
  471. self._con.commit()
  472. except sqlite.DatabaseError, e:
  473. self._con.rollback()
  474. raise DatabaseException(
  475. "SQLite: Error commiting data to db [%s]" % (e))
  476. def _tagids(self, tags):
  477. ids = []
  478. for t in tags:
  479. sql = "SELECT ID FROM TAGS WHERE DATA = ?"
  480. if not isinstance(t, Tag):
  481. raise DatabaseException(
  482. "Tried to insert foreign object into database [%s]", t)
  483. data = cPickle.dumps(t)
  484. try:
  485. self._cur.execute(sql, [data])
  486. row = self._cur.fetchone()
  487. if (row is not None):
  488. ids.append(row[0])
  489. else:
  490. sql = "INSERT INTO TAGS(DATA) VALUES(?)"
  491. self._cur.execute(sql, [data])
  492. ids.append(self._cur.lastrowid)
  493. except sqlite.DatabaseError, e:
  494. raise DatabaseException("SQLite: %s" % (e))
  495. return ids
  496. def _deletenodetags(self, node):
  497. try:
  498. sql = "DELETE FROM LOOKUP WHERE NODE = ?"
  499. self._cur.execute(sql, [node.get_id()])
  500. except sqlite.DatabaseError, e:
  501. raise DatabaseException("SQLite: %s" % (e))
  502. self._commit()
  503. def _setnodetags(self, node):
  504. self._deletenodetags(node)
  505. ids = self._tagids(node.get_tags())
  506. for i in ids:
  507. sql = "INSERT OR REPLACE INTO LOOKUP VALUES(?, ?)"
  508. params = [node.get_id(), i]
  509. try:
  510. self._cur.execute(sql, params)
  511. except sqlite.DatabaseError, e:
  512. raise DatabaseException("SQLite: %s" % (e))
  513. self._commit()
  514. def _checktags(self):
  515. try:
  516. sql = "DELETE FROM TAGS WHERE ID NOT IN (SELECT TAG FROM " \
  517. + "LOOKUP GROUP BY TAG)"
  518. self._cur.execute(sql)
  519. except sqlite.DatabaseError, e:
  520. raise DatabaseException("SQLite: %s" % (e))
  521. self._commit()
  522. def _checktables(self):
  523. """ Check if the Pwman tables exist """
  524. self._cur.execute("PRAGMA TABLE_INFO(NODES)")
  525. if (self._cur.fetchone() is None):
  526. # table doesn't exist, create it
  527. # SQLite does have constraints implemented at the moment
  528. # so datatype will just be a string
  529. self._cur.execute("CREATE TABLE NODES "
  530. "(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
  531. "DATA BLOB NOT NULL)")
  532. self._cur.execute("CREATE TABLE TAGS "
  533. "(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
  534. "DATA BLOB NOT NULL UNIQUE)")
  535. self._cur.execute("CREATE TABLE LOOKUP "
  536. "(NODE INTEGER NOT NULL, TAG INTEGER NOT NULL,"
  537. " PRIMARY KEY(NODE, TAG))")
  538. self._cur.execute("CREATE TABLE KEY "
  539. + "(THEKEY TEXT NOT NULL DEFAULT '')")
  540. self._cur.execute("INSERT INTO KEY VALUES('')")
  541. try:
  542. self._con.commit()
  543. except DatabaseException, e:
  544. self._con.rollback()
  545. raise e
  546. def savekey(self, key):
  547. """
  548. This function is saving the key to table KEY.
  549. The key already arrives as an encrypted string.
  550. It is the same self._keycrypted from
  551. crypto py (check with id(self._keycrypted) and
  552. id(key) here.
  553. """
  554. sql = "UPDATE KEY SET THEKEY = ?"
  555. values = [key]
  556. self._cur.execute(sql, values)
  557. try:
  558. self._con.commit()
  559. except sqlite.DatabaseError, e:
  560. self._con.rollback()
  561. raise DatabaseException(
  562. "SQLite: Error saving key [%s]" % (e))
  563. def loadkey(self):
  564. """
  565. fetch the key to database. the key is also stored
  566. encrypted.
  567. """
  568. self._cur.execute("SELECT THEKEY FROM KEY")
  569. keyrow = self._cur.fetchone()
  570. if (keyrow[0] == ''):
  571. return None
  572. else:
  573. return keyrow[0]