sqlite.py 22 KB

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