sqlite.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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.tags import Tag
  26. import re
  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. class SQLiteDatabase(Database):
  38. """SQLite Database implementation"""
  39. def __init__(self):
  40. """Initialise SQLitePwmanDatabase instance."""
  41. Database.__init__(self)
  42. try:
  43. self._filename = config.get_value('Database', 'filename')
  44. except KeyError, e:
  45. raise DatabaseException(
  46. "SQLite: missing parameter [%s]" % (e))
  47. def _open(self):
  48. try:
  49. self._con = sqlite.connect(self._filename)
  50. self._cur = self._con.cursor()
  51. self._checktables()
  52. except sqlite.DatabaseError, e:
  53. raise DatabaseException("SQLite: %s" % (e))
  54. def close(self):
  55. self._cur.close()
  56. self._con.close()
  57. def listtags(self, alltags=False):
  58. sql = ''
  59. params = []
  60. if len(self._filtertags) == 0 or alltags:
  61. sql = "SELECT DATA FROM TAGS ORDER BY DATA ASC"
  62. else:
  63. sql = ("SELECT TAGS.DATA FROM LOOKUP"
  64. +" INNER JOIN TAGS ON LOOKUP.TAG = TAGS.ID"
  65. +" WHERE NODE IN (")
  66. first = True
  67. # if using the command filter, the code crashes ...
  68. #
  69. for t in self._filtertags:
  70. if not first:
  71. sql += " INTERSECT "
  72. else:
  73. first = False
  74. sql += ("SELECT NODE FROM LOOKUP LEFT JOIN TAGS ON TAG = TAGS.ID "
  75. + " WHERE TAGS.DATA = ?")
  76. params.append(cPickle.dumps(t))
  77. sql += ") EXCEPT SELECT DATA FROM TAGS WHERE "
  78. first = True
  79. for t in self._filtertags:
  80. if not first:
  81. sql += " OR "
  82. else:
  83. first = False
  84. sql += "TAGS.DATA = ?"
  85. params.append(t)
  86. try:
  87. print params
  88. self._cur.execute(sql, params)
  89. tags = []
  90. row = self._cur.fetchone()
  91. while (row != None):
  92. tagstring = str(row[0])
  93. m = re.search('S\"S\'(.+?)\'', tagstring)
  94. if m:
  95. found = m.group(1)
  96. tags.append(Tag(found))
  97. row = self._cur.fetchone()
  98. return tags
  99. except sqlite.DatabaseError, e:
  100. raise DatabaseException("SQLite: %s" % (e))
  101. def getnodes(self, ids):
  102. nodes = []
  103. for i in ids:
  104. sql = "SELECT DATA FROM NODES WHERE ID = ?"
  105. try:
  106. self._cur.execute(sql, [i])
  107. row = self._cur.fetchone()
  108. if row != None:
  109. node = cPickle.loads(str(row[0]))
  110. node.set_id(i)
  111. nodes.append(node)
  112. except sqlite.DatabaseError, e:
  113. raise DatabaseException("SQLite: %s" % (e))
  114. return nodes
  115. def editnode(self, id, node):
  116. if not isinstance(node, Node): raise DatabaseException(
  117. "Tried to insert foreign object into database [%s]" % node)
  118. try:
  119. sql = "UPDATE NODES SET DATA = ? WHERE ID = ?";
  120. self._cur.execute(sql, [cPickle.dumps(node), id])
  121. except sqlite.DatabaseError, e:
  122. raise DatabaseException("SQLite: %s" % (e))
  123. self._setnodetags(node)
  124. self._checktags()
  125. self._commit()
  126. def addnodes(self, nodes):
  127. for n in nodes:
  128. sql = "INSERT INTO NODES(DATA) VALUES(?)"
  129. if not isinstance(n, Node): raise DatabaseException(
  130. "Tried to insert foreign object into database [%s]", n)
  131. value = cPickle.dumps(n)
  132. try:
  133. self._cur.execute(sql, [value])
  134. except sqlite.DatabaseError, e:
  135. raise DatabaseException("SQLite: %s" % (e))
  136. id = self._cur.lastrowid
  137. n.set_id(id)
  138. self._setnodetags(n)
  139. self._commit()
  140. def removenodes(self, nodes):
  141. for n in nodes:
  142. if not isinstance(n, Node): raise DatabaseException(
  143. "Tried to delete foreign object from database [%s]", n)
  144. try:
  145. sql = "DELETE FROM NODES WHERE ID = ?";
  146. self._cur.execute(sql, [n.get_id()])
  147. except sqlite.DatabaseError, e:
  148. raise DatabaseException("SQLite: %s" % (e))
  149. self._deletenodetags(n)
  150. self._checktags()
  151. self._commit()
  152. def listnodes(self):
  153. sql = ''
  154. params = []
  155. if len(self._filtertags) == 0:
  156. sql = "SELECT ID FROM NODES ORDER BY ID ASC"
  157. else:
  158. first = True
  159. for t in self._filtertags:
  160. if not first:
  161. sql += " INTERSECT "
  162. else:
  163. first = False
  164. sql += ("SELECT NODE FROM LOOKUP LEFT JOIN TAGS ON TAG = TAGS.ID"
  165. + " WHERE TAGS.DATA = ? ")
  166. params.append(cPickle.dumps(t))
  167. try:
  168. self._cur.execute(sql, params)
  169. ids = []
  170. row = self._cur.fetchone()
  171. while (row != None):
  172. ids.append(row[0])
  173. row = self._cur.fetchone()
  174. return ids
  175. except sqlite.DatabaseError, e:
  176. raise DatabaseException("SQLite: %s" % (e))
  177. def _commit(self):
  178. try:
  179. self._con.commit()
  180. except sqlite.DatabaseError, e:
  181. self._con.rollback()
  182. raise DatabaseException(
  183. "SQLite: Error commiting data to db [%s]" % (e))
  184. def _tagids(self, tags):
  185. ids = []
  186. for t in tags:
  187. sql = "SELECT ID FROM TAGS WHERE DATA = ?"
  188. if not isinstance(t, Tag): raise DatabaseException(
  189. "Tried to insert foreign object into database [%s]", t)
  190. data = cPickle.dumps(t)
  191. try:
  192. self._cur.execute(sql, [data])
  193. row = self._cur.fetchone()
  194. if (row != None):
  195. ids.append(row[0])
  196. else:
  197. sql = "INSERT INTO TAGS(DATA) VALUES(?)"
  198. self._cur.execute(sql, [data])
  199. ids.append(self._cur.lastrowid)
  200. except sqlite.DatabaseError, e:
  201. raise DatabaseException("SQLite: %s" % (e))
  202. return ids
  203. def _deletenodetags(self, node):
  204. try:
  205. sql = "DELETE FROM LOOKUP WHERE NODE = ?"
  206. self._cur.execute(sql, [node.get_id()])
  207. except sqlite.DatabaseError, e:
  208. raise DatabaseException("SQLite: %s" % (e))
  209. self._commit()
  210. def _setnodetags(self, node):
  211. self._deletenodetags(node)
  212. ids = self._tagids(node.get_tags())
  213. for i in ids:
  214. sql = "INSERT OR REPLACE INTO LOOKUP VALUES(?, ?)"
  215. params = [node.get_id(), i]
  216. try:
  217. self._cur.execute(sql, params)
  218. except sqlite.DatabaseError, e:
  219. raise DatabaseException("SQLite: %s" % (e))
  220. self._commit()
  221. def _checktags(self):
  222. try:
  223. sql = "DELETE FROM TAGS WHERE ID NOT IN (SELECT TAG FROM LOOKUP GROUP BY TAG)"
  224. self._cur.execute(sql)
  225. except sqlite.DatabaseError, e:
  226. raise DatabaseException("SQLite: %s" % (e))
  227. self._commit()
  228. def _checktables(self):
  229. """ Check if the Pwman tables exist """
  230. self._cur.execute("PRAGMA TABLE_INFO(NODES)")
  231. if (self._cur.fetchone() == None):
  232. # table doesn't exist, create it
  233. # SQLite does have constraints implemented at the moment
  234. # so datatype will just be a string
  235. self._cur.execute("CREATE TABLE NODES"
  236. + "(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
  237. + "DATA BLOB NOT NULL)")
  238. self._cur.execute("CREATE TABLE TAGS"
  239. + "(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
  240. + "DATA BLOB NOT NULL UNIQUE)")
  241. self._cur.execute("CREATE TABLE LOOKUP"
  242. + "(NODE INTEGER NOT NULL, TAG INTEGER NOT NULL,"
  243. + " PRIMARY KEY(NODE, TAG))")
  244. self._cur.execute("CREATE TABLE KEY"
  245. + "(THEKEY TEXT NOT NULL DEFAULT '')");
  246. self._cur.execute("INSERT INTO KEY VALUES('')");
  247. try:
  248. self._con.commit()
  249. except DatabaseError, e:
  250. self._con.rollback()
  251. raise e
  252. def savekey(self, key):
  253. """
  254. This function is saving the key to table KEY.
  255. The key already arrives as an encrypted string.
  256. """
  257. sql = "UPDATE KEY SET THEKEY = ?"
  258. values = [key]
  259. self._cur.execute(sql, values)
  260. try:
  261. self._con.commit()
  262. except sqlite.DatabaseError, e:
  263. self._con.rollback()
  264. raise DatabaseException(
  265. "SQLite: Error saving key [%s]" % (e))
  266. def loadkey(self):
  267. """
  268. fetch the key to database. the key is also stored
  269. encrypted.
  270. """
  271. self._cur.execute("SELECT THEKEY FROM KEY");
  272. keyrow = self._cur.fetchone()
  273. if (keyrow[0] == ''):
  274. return None
  275. else:
  276. return keyrow[0]