test_converter.py 10 KB

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