sqlite.py 22 KB

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