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