osqlite.py 11 KB

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