test_converter.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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.nodes import NewNode
  27. from pwman.util.crypto import CryptoEngine
  28. from pwman.data.tags import Tag
  29. from db_tests import node_factory
  30. from pwman.util.callback import CLICallback
  31. import sqlite3 as sqlite
  32. import pwman.util.config as config
  33. from pwman import default_config
  34. import cPickle
  35. from test_tools import SetupTester
  36. class SQLiteDatabase(Database):
  37. """SQLite Database implementation"""
  38. def __init__(self, fname):
  39. """Initialise SQLitePwmanDatabase instance."""
  40. Database.__init__(self)
  41. try:
  42. self._filename = fname
  43. except KeyError as e:
  44. raise DatabaseException(
  45. "SQLite: missing parameter [%s]" % (e))
  46. def _open(self):
  47. try:
  48. self._con = sqlite.connect(self._filename)
  49. self._cur = self._con.cursor()
  50. self._checktables()
  51. except sqlite.DatabaseError as e:
  52. raise DatabaseException("SQLite: %s" % (e))
  53. def close(self):
  54. self._cur.close()
  55. self._con.close()
  56. def listtags(self, all=False):
  57. sql = ''
  58. params = []
  59. if len(self._filtertags) == 0 or all:
  60. sql = "SELECT DATA FROM TAGS ORDER BY DATA ASC"
  61. else:
  62. sql = ("SELECT TAGS.DATA FROM LOOKUP"
  63. + " INNER JOIN TAGS ON LOOKUP.TAG = TAGS.ID"
  64. + " WHERE NODE IN (")
  65. first = True
  66. for t in self._filtertags:
  67. if not first:
  68. sql += " INTERSECT "
  69. else:
  70. first = False
  71. sql += (("SELECT NODE FROM LOOKUP OUTER JOIN TAGS ON "
  72. "TAG = TAGS.ID "
  73. " WHERE TAGS.DATA = ?"))
  74. params.append(cPickle.dumps(t))
  75. sql += ") EXCEPT SELECT DATA FROM TAGS WHERE "
  76. first = True
  77. for t in self._filtertags:
  78. if not first:
  79. sql += " OR "
  80. else:
  81. first = False
  82. sql += "TAGS.DATA = ?"
  83. params.append(cPickle.dumps(t))
  84. try:
  85. self._cur.execute(sql, params)
  86. tags = []
  87. row = self._cur.fetchone()
  88. while (row is not None):
  89. tag = cPickle.loads(str(row[0]))
  90. tags.append(tag)
  91. row = self._cur.fetchone()
  92. return tags
  93. except sqlite.DatabaseError as e:
  94. raise DatabaseException("SQLite: %s" % (e))
  95. def getnodes(self, ids):
  96. nodes = []
  97. for i in ids:
  98. sql = "SELECT DATA FROM NODES WHERE ID = ?"
  99. try:
  100. self._cur.execute(sql, [i])
  101. row = self._cur.fetchone()
  102. if row is not None:
  103. node = cPickle.loads(str(row[0]))
  104. node.set_id(i)
  105. nodes.append(node)
  106. except sqlite.DatabaseError as e:
  107. raise DatabaseException("SQLite: %s" % (e))
  108. return nodes
  109. def editnode(self, id, node):
  110. if not isinstance(node, Node):
  111. raise DatabaseException(
  112. "Tried to insert foreign object into database [%s]" % node)
  113. try:
  114. sql = "UPDATE NODES SET DATA = ? WHERE ID = ?"
  115. self._cur.execute(sql, [cPickle.dumps(node), id])
  116. except sqlite.DatabaseError as e:
  117. raise DatabaseException("SQLite: %s" % (e))
  118. self._setnodetags(node)
  119. self._checktags()
  120. self._commit()
  121. def addnodes(self, nodes):
  122. for n in nodes:
  123. sql = "INSERT INTO NODES(DATA) VALUES(?)"
  124. if not isinstance(n, Node):
  125. raise DatabaseException(("Tried to insert foreign object"
  126. "into database [%s]", n))
  127. value = cPickle.dumps(n)
  128. try:
  129. self._cur.execute(sql, [value])
  130. except sqlite.DatabaseError as e:
  131. raise DatabaseException("SQLite: %s" % (e))
  132. id = self._cur.lastrowid
  133. n.set_id(id)
  134. self._setnodetags(n)
  135. self._commit()
  136. def removenodes(self, nodes):
  137. for n in nodes:
  138. if not isinstance(n, Node):
  139. raise DatabaseException(
  140. "Tried to delete foreign object from database [%s]", n)
  141. try:
  142. sql = "DELETE FROM NODES WHERE ID = ?"
  143. self._cur.execute(sql, [n.get_id()])
  144. except sqlite.DatabaseError as e:
  145. raise DatabaseException("SQLite: %s" % (e))
  146. self._deletenodetags(n)
  147. self._checktags()
  148. self._commit()
  149. def listnodes(self):
  150. sql = ''
  151. params = []
  152. if len(self._filtertags) == 0:
  153. sql = "SELECT ID FROM NODES ORDER BY ID ASC"
  154. else:
  155. first = True
  156. for t in self._filtertags:
  157. if not first:
  158. sql += " INTERSECT "
  159. else:
  160. first = False
  161. sql += ("SELECT NODE FROM LOOKUP OUTER JOIN "
  162. "TAGS ON TAG = TAGS.ID"
  163. " WHERE TAGS.DATA = ? ")
  164. params.append(cPickle.dumps(t))
  165. try:
  166. self._cur.execute(sql, params)
  167. ids = []
  168. row = self._cur.fetchone()
  169. while (row is not None):
  170. ids.append(row[0])
  171. row = self._cur.fetchone()
  172. return ids
  173. except sqlite.DatabaseError as e:
  174. raise DatabaseException("SQLite: %s" % (e))
  175. def _commit(self):
  176. try:
  177. self._con.commit()
  178. except sqlite.DatabaseError as e:
  179. self._con.rollback()
  180. raise DatabaseException(
  181. "SQLite: Error commiting data to db [%s]" % (e))
  182. def _tagids(self, tags):
  183. ids = []
  184. for t in tags:
  185. sql = "SELECT ID FROM TAGS WHERE DATA = ?"
  186. if not isinstance(t, Tag):
  187. raise DatabaseException("Tried to insert foreign "
  188. "object into database [%s]", t)
  189. data = cPickle.dumps(t)
  190. try:
  191. self._cur.execute(sql, [data])
  192. row = self._cur.fetchone()
  193. if (row is not None):
  194. ids.append(row[0])
  195. else:
  196. sql = "INSERT INTO TAGS(DATA) VALUES(?)"
  197. self._cur.execute(sql, [data])
  198. ids.append(self._cur.lastrowid)
  199. except sqlite.DatabaseError as e:
  200. raise DatabaseException("SQLite: %s" % (e))
  201. return ids
  202. def _deletenodetags(self, node):
  203. try:
  204. sql = "DELETE FROM LOOKUP WHERE NODE = ?"
  205. self._cur.execute(sql, [node.get_id()])
  206. except sqlite.DatabaseError as e:
  207. raise DatabaseException("SQLite: %s" % (e))
  208. self._commit()
  209. def _setnodetags(self, node):
  210. self._deletenodetags(node)
  211. ids = self._tagids(node.get_tags())
  212. for i in ids:
  213. sql = "INSERT OR REPLACE INTO LOOKUP VALUES(?, ?)"
  214. params = [node.get_id(), i]
  215. try:
  216. self._cur.execute(sql, params)
  217. except sqlite.DatabaseError as e:
  218. raise DatabaseException("SQLite: %s" % (e))
  219. self._commit()
  220. def _checktags(self):
  221. try:
  222. sql = ("DELETE FROM TAGS WHERE ID NOT "
  223. "IN (SELECT TAG FROM LOOKUP GROUP BY TAG)")
  224. self._cur.execute(sql)
  225. except sqlite.DatabaseError as 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() is 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 DatabaseException as e:
  250. self._con.rollback()
  251. raise e
  252. def savekey(self, key):
  253. sql = "UPDATE KEY SET THEKEY = ?"
  254. values = [key]
  255. self._cur.execute(sql, values)
  256. try:
  257. self._con.commit()
  258. except sqlite.DatabaseError as e:
  259. self._con.rollback()
  260. raise DatabaseException(
  261. "SQLite: Error saving key [%s]" % (e))
  262. def loadkey(self):
  263. self._cur.execute("SELECT THEKEY FROM KEY")
  264. keyrow = self._cur.fetchone()
  265. if (keyrow[0] == ''):
  266. return None
  267. else:
  268. return keyrow[0]
  269. class CreateTestDataBases(object):
  270. def __init__(self):
  271. config.set_defaults(default_config)
  272. enc = CryptoEngine.get()
  273. enc.set_callback(CLICallback())
  274. self.db1 = SQLiteDatabaseNewForm('konverter-v0.4.db', dbformat=0.4)
  275. self.db2 = SQLiteDatabaseNewForm('konverter-v0.5.db', dbformat=0.5)
  276. def open_dbs(self):
  277. self.db1._open()
  278. self.db2._open()
  279. self.db1.close()
  280. self.db2.close()
  281. def add_nodes_to_db1(self):
  282. username = 'tester'
  283. password = 'Password'
  284. url = 'example.org'
  285. notes = 'some notes'
  286. node = node_factory(username, password, url, notes,
  287. ['testing1', 'testing2'])
  288. self.db1.addnodes([node])
  289. idx_created = node._id
  290. new_node = self.db1.getnodes([idx_created])[0]
  291. for key, attr in {'password': password, 'username': username,
  292. 'url': url, 'notes': notes}.iteritems():
  293. assert attr == getattr(new_node, key)
  294. self.db1.close()
  295. def add_nodes_to_db2(self):
  296. username = 'tester'
  297. password = 'Password'
  298. url = 'example.org'
  299. notes = 'some notes'
  300. node = node_factory(username, password, url, notes,
  301. ['testing1', 'testing2'])
  302. self.db2.addnodes([node])
  303. idx_created = node._id
  304. new_node = self.db2.getnodes([idx_created])[0]
  305. for key, attr in {'password': password, 'username': username,
  306. 'url': url, 'notes': notes}.iteritems():
  307. assert attr == getattr(new_node, key)
  308. self.db2.close()
  309. def run(self):
  310. # before add nodes to db1 we have to create an encryption key!
  311. # this is handeld by the open method
  312. self.db1.open()
  313. self.add_nodes_to_db1()
  314. self.db2.open()
  315. self.add_nodes_to_db2()
  316. if __name__ == '__main__':
  317. tester = CreateTestDataBases()
  318. tester.run()