sqlite.py 22 KB

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