sqlite.py 22 KB

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