test_converter.py 11 KB

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