sqlite.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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. if len(self._filtertags) == 0:
  187. sql = "SELECT ID FROM NODES ORDER BY ID ASC"
  188. else:
  189. first = True
  190. for t in self._filtertags:
  191. if not first:
  192. sql += " INTERSECT "
  193. else:
  194. first = False
  195. sql += ("SELECT NODE FROM LOOKUP LEFT JOIN TAGS ON TAG = "
  196. " TAGS.ID WHERE TAGS.DATA = ? ")
  197. params = [t.name.strip()]
  198. try:
  199. self._cur.execute(sql, params)
  200. rows = self._cur.fetchall()
  201. ids = [row[0] for row in rows]
  202. return ids
  203. except sqlite.DatabaseError, e:
  204. raise DatabaseException("SQLite: %s" % (e))
  205. def _commit(self):
  206. try:
  207. self._con.commit()
  208. except sqlite.DatabaseError, e:
  209. self._con.rollback()
  210. raise DatabaseException(
  211. "SQLite: Error commiting data to db [%s]" % (e))
  212. def _create_tag(self, tag, node_ids):
  213. """add tags to db"""
  214. sql = "INSERT OR REPLACE INTO TAGS(DATA) VALUES(?)"
  215. if isinstance(tag, str):
  216. self._cur.execute(sql, [tag])
  217. else:
  218. self._cur.execute(sql, [tag._name])
  219. def _update_tag_lookup(self, node, tag_id):
  220. sql = "INSERT OR REPLACE INTO LOOKUP VALUES(?, ?)"
  221. params = [node._id, tag_id]
  222. try:
  223. self._cur.execute(sql, params)
  224. except sqlite.DatabaseError, e:
  225. raise DatabaseException("SQLite: %s" % (e))
  226. def _tagids(self, tags):
  227. ids = []
  228. sql = "SELECT ID FROM TAGS WHERE DATA = ?"
  229. for tag in tags:
  230. try:
  231. if isinstance(tag, str):
  232. self._cur.execute(sql, [tag])
  233. else:
  234. self._cur.execute(sql, [tag._name])
  235. row = self._cur.fetchone()
  236. if (row is not None):
  237. ids.append(row[0])
  238. else:
  239. self._create_tag(tag, None)
  240. ids.append(self._cur.lastrowid)
  241. except sqlite.DatabaseError, e:
  242. raise DatabaseException("SQLite: %s" % (e))
  243. return ids
  244. def _deletenodetags(self, node):
  245. try:
  246. sql = "DELETE FROM LOOKUP WHERE NODE = ?"
  247. self._cur.execute(sql, [node._id])
  248. except sqlite.DatabaseError, e:
  249. raise DatabaseException("SQLite: %s" % (e))
  250. self._commit()
  251. def _setnodetags(self, node):
  252. self._deletenodetags(node)
  253. ids = self._tagids(node.tags)
  254. for tagid in ids:
  255. self._update_tag_lookup(node, tagid)
  256. self._commit()
  257. def _checktags(self):
  258. try:
  259. sql = "DELETE FROM TAGS WHERE ID NOT IN (SELECT TAG FROM" \
  260. + " LOOKUP GROUP BY TAG)"
  261. self._cur.execute(sql)
  262. except sqlite.DatabaseError, e:
  263. raise DatabaseException("SQLite: %s" % (e))
  264. self._commit()
  265. def _checktables(self):
  266. """
  267. Check if the Pwman tables exist.
  268. TODO: This method should check the version of the
  269. database. If it finds an old format it should
  270. exis, and prompt the user to convert the database
  271. to the new version with a designated script.
  272. """
  273. self._cur.execute("PRAGMA TABLE_INFO(NODES)")
  274. if (self._cur.fetchone() is None):
  275. # table doesn't exist, create it
  276. # SQLite does have constraints implemented at the moment
  277. # so datatype will just be a string
  278. self._cur.execute("CREATE TABLE NODES (ID INTEGER PRIMARY KEY"
  279. + " AUTOINCREMENT,DATA BLOB NOT NULL)")
  280. self._cur.execute("CREATE TABLE TAGS"
  281. + "(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
  282. + "DATA BLOB NOT NULL UNIQUE)")
  283. self._cur.execute("CREATE TABLE LOOKUP"
  284. + "(NODE INTEGER NOT NULL, TAG INTEGER NOT NULL,"
  285. + " PRIMARY KEY(NODE, TAG))")
  286. self._cur.execute("CREATE TABLE KEY"
  287. + "(THEKEY TEXT NOT NULL DEFAULT '')")
  288. self._cur.execute("INSERT INTO KEY VALUES('')")
  289. # create a table to hold DB version info
  290. self._cur.execute("CREATE TABLE DBVERSION"
  291. + "(DBVERSION TEXT NOT NULL DEFAULT '0.4')")
  292. self._cur.execute("INSERT INTO DBVERSION VALUES('0.4')")
  293. try:
  294. self._con.commit()
  295. except DatabaseException, e:
  296. self._con.rollback()
  297. raise e
  298. def savekey(self, key):
  299. """
  300. This function is saving the key to table KEY.
  301. The key already arrives as an encrypted string.
  302. It is the same self._keycrypted from
  303. crypto py (check with id(self._keycrypted) and
  304. id(key) here.
  305. """
  306. sql = "UPDATE KEY SET THEKEY = ?"
  307. values = [key]
  308. self._cur.execute(sql, values)
  309. try:
  310. self._con.commit()
  311. except sqlite.DatabaseError, e:
  312. self._con.rollback()
  313. raise DatabaseException(
  314. "SQLite: Error saving key [%s]" % (e))
  315. def loadkey(self):
  316. """
  317. fetch the key to database. the key is also stored
  318. encrypted.
  319. """
  320. self._cur.execute("SELECT THEKEY FROM KEY")
  321. keyrow = self._cur.fetchone()
  322. if (keyrow[0] == ''):
  323. return None
  324. else:
  325. return keyrow[0]
  326. class SQLiteDatabase(Database):
  327. """SQLite Database implementation"""
  328. def __init__(self):
  329. """Initialise SQLitePwmanDatabase instance."""
  330. Database.__init__(self)
  331. try:
  332. self._filename = config.get_value('Database', 'filename')
  333. except KeyError, e:
  334. raise DatabaseException(
  335. "SQLite: missing parameter [%s]" % (e))
  336. def _open(self):
  337. try:
  338. self._con = sqlite.connect(self._filename)
  339. self._cur = self._con.cursor()
  340. self._checktables()
  341. except sqlite.DatabaseError, e:
  342. raise DatabaseException("SQLite: %s" % (e))
  343. def close(self):
  344. self._cur.close()
  345. self._con.close()
  346. def listtags(self, alltags=False):
  347. sql = ''
  348. params = []
  349. if len(self._filtertags) == 0 or alltags:
  350. sql = "SELECT DATA FROM TAGS ORDER BY DATA ASC"
  351. else:
  352. sql = ("SELECT TAGS.DATA FROM LOOKUP"
  353. + " INNER JOIN TAGS ON LOOKUP.TAG = TAGS.ID"
  354. + " WHERE NODE IN (")
  355. first = True
  356. # if using the command filter, the code crashes ...
  357. #
  358. for t in self._filtertags:
  359. if not first:
  360. sql += " INTERSECT "
  361. else:
  362. first = False
  363. sql += ("SELECT NODE FROM LOOKUP LEFT JOIN TAGS ON TAG " +
  364. + " = TAGS.ID "
  365. + " WHERE TAGS.DATA = ?")
  366. params.append(cPickle.dumps(t))
  367. sql += ") EXCEPT SELECT DATA FROM TAGS WHERE "
  368. first = True
  369. for t in self._filtertags:
  370. if not first:
  371. sql += " OR "
  372. else:
  373. first = False
  374. sql += "TAGS.DATA = ?"
  375. params.append(t)
  376. try:
  377. print params
  378. self._cur.execute(sql, params)
  379. tags = []
  380. row = self._cur.fetchone()
  381. while (row is not None):
  382. tag = cPickle.loads(str(row[0]))
  383. tags.append(tag)
  384. row = self._cur.fetchone()
  385. return tags
  386. except sqlite.DatabaseError, e:
  387. raise DatabaseException("SQLite: %s" % (e))
  388. def getnodes(self, ids):
  389. nodes = []
  390. for i in ids:
  391. sql = "SELECT DATA FROM NODES WHERE ID = ?"
  392. try:
  393. self._cur.execute(sql, [i])
  394. row = self._cur.fetchone()
  395. if row is not None:
  396. node = cPickle.loads(str(row[0]))
  397. node.set_id(i)
  398. nodes.append(node)
  399. except sqlite.DatabaseError, e:
  400. raise DatabaseException("SQLite: %s" % (e))
  401. return nodes
  402. def editnode(self, id, node):
  403. if not isinstance(node, Node):
  404. raise DatabaseException(
  405. "Tried to insert foreign object into database [%s]" % node)
  406. try:
  407. sql = "UPDATE NODES SET DATA = ? WHERE ID = ?"
  408. self._cur.execute(sql, [cPickle.dumps(node), id])
  409. except sqlite.DatabaseError, e:
  410. raise DatabaseException("SQLite: %s" % (e))
  411. self._setnodetags(node)
  412. self._checktags()
  413. self._commit()
  414. def addnodes(self, nodes):
  415. for n in nodes:
  416. sql = "INSERT INTO NODES(DATA) VALUES(?)"
  417. if not isinstance(n, Node):
  418. raise DatabaseException(
  419. "Tried to insert foreign object into database [%s]", n)
  420. value = cPickle.dumps(n)
  421. try:
  422. self._cur.execute(sql, [value])
  423. except sqlite.DatabaseError, e:
  424. raise DatabaseException("SQLite: %s" % (e))
  425. id = self._cur.lastrowid
  426. n.set_id(id)
  427. self._setnodetags(n)
  428. self._commit()
  429. def removenodes(self, nodes):
  430. for n in nodes:
  431. if not isinstance(n, Node):
  432. raise DatabaseException(
  433. "Tried to delete foreign object from database [%s]", n)
  434. try:
  435. sql = "DELETE FROM NODES WHERE ID = ?"
  436. self._cur.execute(sql, [n.get_id()])
  437. except sqlite.DatabaseError, e:
  438. raise DatabaseException("SQLite: %s" % (e))
  439. self._deletenodetags(n)
  440. self._checktags()
  441. self._commit()
  442. def listnodes(self):
  443. sql = ''
  444. params = []
  445. if len(self._filtertags) == 0:
  446. sql = "SELECT ID FROM NODES ORDER BY ID ASC"
  447. else:
  448. first = True
  449. for t in self._filtertags:
  450. if not first:
  451. sql += " INTERSECT "
  452. else:
  453. first = False
  454. sql += ("SELECT NODE FROM LOOKUP LEFT JOIN TAGS "
  455. + " ON TAG = TAGS.ID"
  456. + " WHERE TAGS.DATA = ? ")
  457. params.append(cPickle.dumps(t))
  458. try:
  459. self._cur.execute(sql, params)
  460. ids = []
  461. row = self._cur.fetchone()
  462. while (row is not None):
  463. ids.append(row[0])
  464. row = self._cur.fetchone()
  465. return ids
  466. except sqlite.DatabaseError, e:
  467. raise DatabaseException("SQLite: %s" % (e))
  468. def _commit(self):
  469. try:
  470. self._con.commit()
  471. except sqlite.DatabaseError, e:
  472. self._con.rollback()
  473. raise DatabaseException(
  474. "SQLite: Error commiting data to db [%s]" % (e))
  475. def _tagids(self, tags):
  476. ids = []
  477. for t in tags:
  478. sql = "SELECT ID FROM TAGS WHERE DATA = ?"
  479. if not isinstance(t, Tag):
  480. raise DatabaseException(
  481. "Tried to insert foreign object into database [%s]", t)
  482. data = cPickle.dumps(t)
  483. try:
  484. self._cur.execute(sql, [data])
  485. row = self._cur.fetchone()
  486. if (row is not None):
  487. ids.append(row[0])
  488. else:
  489. sql = "INSERT INTO TAGS(DATA) VALUES(?)"
  490. self._cur.execute(sql, [data])
  491. ids.append(self._cur.lastrowid)
  492. except sqlite.DatabaseError, e:
  493. raise DatabaseException("SQLite: %s" % (e))
  494. return ids
  495. def _deletenodetags(self, node):
  496. try:
  497. sql = "DELETE FROM LOOKUP WHERE NODE = ?"
  498. self._cur.execute(sql, [node.get_id()])
  499. except sqlite.DatabaseError, e:
  500. raise DatabaseException("SQLite: %s" % (e))
  501. self._commit()
  502. def _setnodetags(self, node):
  503. self._deletenodetags(node)
  504. ids = self._tagids(node.get_tags())
  505. for i in ids:
  506. sql = "INSERT OR REPLACE INTO LOOKUP VALUES(?, ?)"
  507. params = [node.get_id(), i]
  508. try:
  509. self._cur.execute(sql, params)
  510. except sqlite.DatabaseError, e:
  511. raise DatabaseException("SQLite: %s" % (e))
  512. self._commit()
  513. def _checktags(self):
  514. try:
  515. sql = "DELETE FROM TAGS WHERE ID NOT IN (SELECT TAG FROM " \
  516. + "LOOKUP GROUP BY TAG)"
  517. self._cur.execute(sql)
  518. except sqlite.DatabaseError, e:
  519. raise DatabaseException("SQLite: %s" % (e))
  520. self._commit()
  521. def _checktables(self):
  522. """ Check if the Pwman tables exist """
  523. self._cur.execute("PRAGMA TABLE_INFO(NODES)")
  524. if (self._cur.fetchone() is None):
  525. # table doesn't exist, create it
  526. # SQLite does have constraints implemented at the moment
  527. # so datatype will just be a string
  528. self._cur.execute("CREATE TABLE NODES "
  529. "(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
  530. "DATA BLOB NOT NULL)")
  531. self._cur.execute("CREATE TABLE TAGS "
  532. "(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
  533. "DATA BLOB NOT NULL UNIQUE)")
  534. self._cur.execute("CREATE TABLE LOOKUP "
  535. "(NODE INTEGER NOT NULL, TAG INTEGER NOT NULL,"
  536. " PRIMARY KEY(NODE, TAG))")
  537. self._cur.execute("CREATE TABLE KEY "
  538. + "(THEKEY TEXT NOT NULL DEFAULT '')")
  539. self._cur.execute("INSERT INTO KEY VALUES('')")
  540. try:
  541. self._con.commit()
  542. except DatabaseException, e:
  543. self._con.rollback()
  544. raise e
  545. def savekey(self, key):
  546. """
  547. This function is saving the key to table KEY.
  548. The key already arrives as an encrypted string.
  549. It is the same self._keycrypted from
  550. crypto py (check with id(self._keycrypted) and
  551. id(key) here.
  552. """
  553. sql = "UPDATE KEY SET THEKEY = ?"
  554. values = [key]
  555. self._cur.execute(sql, values)
  556. try:
  557. self._con.commit()
  558. except sqlite.DatabaseError, e:
  559. self._con.rollback()
  560. raise DatabaseException(
  561. "SQLite: Error saving key [%s]" % (e))
  562. def loadkey(self):
  563. """
  564. fetch the key to database. the key is also stored
  565. encrypted.
  566. """
  567. self._cur.execute("SELECT THEKEY FROM KEY")
  568. keyrow = self._cur.fetchone()
  569. if (keyrow[0] == ''):
  570. return None
  571. else:
  572. return keyrow[0]