sqlite.py 10 KB

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