sqlite.py 22 KB

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