sqlite.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. #============================================================================
  2. # This file is part of Pwman3.
  3. #
  4. # Pwman3 is free software; you can redistribute iut 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.database import __DB_FORMAT__
  25. from pwman.data.nodes import NewNode
  26. from pwman.data.tags import TagNew
  27. from pwman.util.crypto_engine import CryptoEngine
  28. import sqlite3 as sqlite
  29. import itertools
  30. class SQLiteDatabaseNewForm(Database):
  31. """SQLite Database implementation"""
  32. @classmethod
  33. def check_db_version(cls, fname):
  34. """
  35. check the data base version.
  36. """
  37. con = sqlite.connect(fname)
  38. cur = con.cursor()
  39. cur.execute("PRAGMA TABLE_INFO(DBVERSION)")
  40. row = cur.fetchone()
  41. if not row:
  42. return "0.3" # pragma: no cover
  43. try:
  44. return row[-2]
  45. except IndexError: # pragma: no cover
  46. raise DatabaseException("Something seems fishy with the DB")
  47. def __init__(self, filename, dbformat=__DB_FORMAT__):
  48. """Initialise SQLitePwmanDatabase instance."""
  49. super(SQLiteDatabaseNewForm, self).__init__()
  50. self._filename = filename
  51. self.dbformat = dbformat
  52. def _open(self):
  53. try:
  54. self._con = sqlite.connect(self._filename)
  55. self._cur = self._con.cursor()
  56. self._checktables()
  57. except sqlite.DatabaseError as e: # pragma: no cover
  58. raise DatabaseException("SQLite: %s" % (e))
  59. def close(self):
  60. self._cur.close()
  61. self._con.close()
  62. def listtags(self, alltags=False):
  63. sql = ''
  64. params = []
  65. if not self._filtertags or alltags:
  66. sql = "SELECT DATA FROM TAGS ORDER BY DATA ASC"
  67. else:
  68. sql = ("SELECT TAGS.DATA FROM LOOKUP"
  69. " INNER JOIN TAGS ON LOOKUP.TAG = TAGS.ID"
  70. " WHERE NODE IN (")
  71. first = True
  72. for t in self._filtertags:
  73. if not first:
  74. sql += " INTERSECT " # pragma: no cover
  75. else:
  76. first = False
  77. sql += ("SELECT NODE FROM LOOKUP LEFT JOIN TAGS ON TAG = "
  78. " TAGS.ID WHERE TAGS.DATA LIKE ?")
  79. params.append(t._name.decode()+u'%')
  80. sql += ") EXCEPT SELECT DATA FROM TAGS WHERE "
  81. first = True
  82. for t in self._filtertags:
  83. if not first:
  84. sql += " OR " # pragma: no cover
  85. else:
  86. first = False
  87. sql += "TAGS.DATA = ?"
  88. params.append(t.name)
  89. try:
  90. self._cur.execute(sql, params)
  91. tags = [str(t[0]) for t in self._cur.fetchall()]
  92. return tags
  93. except sqlite.DatabaseError as e: # pragma: no cover
  94. raise DatabaseException("SQLite: %s" % (e))
  95. except sqlite.InterfaceError as e: # pragma: no cover
  96. raise e
  97. def parse_node_string(self, string):
  98. nodestring = string.split("##")
  99. keyvals = {}
  100. for pair in nodestring[:-1]:
  101. key, val = pair.split(":")
  102. keyvals[key.lstrip('##')] = val
  103. tags = nodestring[-1]
  104. tags = tags.split("tags:", 1)[1]
  105. tags = tags.split("tag:")
  106. tags = [tag.split('**endtag**')[0] for tag in tags]
  107. return keyvals, tags
  108. def getnodes(self, ids):
  109. """
  110. object should always be: (ipwman.data.nodes
  111. """
  112. nodes = []
  113. for i in ids:
  114. sql = "SELECT DATA FROM NODES WHERE ID = ?"
  115. self._cur.execute(sql, [i])
  116. row = self._cur.fetchone()
  117. if row is not None:
  118. nodestring = str(row[0])
  119. args, tags = self.parse_node_string(nodestring)
  120. node = NewNode()
  121. node._password = args['password']
  122. node._username = args['username']
  123. node._url = args['url']
  124. node._notes = args['notes']
  125. node.tags = tags
  126. node._id = i
  127. nodes.append(node)
  128. return nodes
  129. def editnode(self, id, node):
  130. try:
  131. sql = "UPDATE NODES SET DATA = ? WHERE ID = ?"
  132. self._cur.execute(sql, [node.dump_edit_to_db()[0], id])
  133. except sqlite.DatabaseError as e: # pragma: no cover
  134. raise DatabaseException("SQLite: %s" % (e))
  135. self._setnodetags(node)
  136. self._checktags()
  137. self._commit()
  138. def addnodes(self, nodes):
  139. """
  140. This method writes the data as an ecrypted string to
  141. the database
  142. """
  143. for n in nodes:
  144. sql = "INSERT INTO NODES(DATA) VALUES(?)"
  145. value = n.dump_edit_to_db()
  146. try:
  147. self._cur.execute(sql, value)
  148. except sqlite.DatabaseError as e: # pragma: no cover
  149. raise DatabaseException("SQLite: %s" % (e))
  150. idx = self._cur.lastrowid
  151. n._id = idx
  152. self._setnodetags(n)
  153. self._commit()
  154. def removenodes(self, nodes):
  155. for n in nodes:
  156. # if not isinstance(n, Node): raise DatabaseException(
  157. # "Tried to delete foreign object from database [%s]", n)
  158. try:
  159. sql = "DELETE FROM NODES WHERE ID = ?"
  160. self._cur.execute(sql, [n._id])
  161. except sqlite.DatabaseError as e: # pragma: no cover
  162. raise DatabaseException("SQLite: %s" % (e))
  163. self._deletenodetags(n)
  164. self._checktags()
  165. self._commit()
  166. def listnodes(self):
  167. sql = ''
  168. params = []
  169. if not self._filtertags:
  170. sql = "SELECT ID FROM NODES ORDER BY ID ASC"
  171. else:
  172. first = True
  173. for t in self._filtertags:
  174. if not first:
  175. sql += " INTERSECT " # pragma: no cover
  176. else:
  177. first = False
  178. sql += ("SELECT NODE FROM LOOKUP LEFT JOIN TAGS ON TAG = "
  179. " TAGS.ID WHERE TAGS.DATA LIKE ? ")
  180. # this is correct if tags are ciphertext
  181. p = t._name.strip()
  182. # this is wrong, it will work when tags are stored as plain
  183. # text
  184. # p = t.name.strip()
  185. p = '%'+p+'%'
  186. params = [p]
  187. try:
  188. self._cur.execute(sql, params)
  189. rows = self._cur.fetchall()
  190. ids = [row[0] for row in rows]
  191. return ids
  192. except sqlite.DatabaseError as e: # pragma: no cover
  193. raise DatabaseException("SQLite: %s" % (e))
  194. def _commit(self):
  195. try:
  196. self._con.commit()
  197. except sqlite.DatabaseError as e: # pragma: no cover
  198. self._con.rollback()
  199. raise DatabaseException(
  200. "SQLite: Error commiting data to db [%s]" % (e))
  201. def _create_tag(self, tag):
  202. """add tags to db"""
  203. # sql = "INSERT OR REPLACE INTO TAGS(DATA) VALUES(?)"
  204. sql = "INSERT OR IGNORE INTO TAGS(DATA) VALUES(?)"
  205. if isinstance(tag, str):
  206. self._cur.execute(sql, [tag])
  207. elif isinstance(tag, TagNew):
  208. self._cur.execute(sql, [tag._name])
  209. else:
  210. self._cur.execute(sql, [tag.decode()])
  211. def _deletenodetags(self, node):
  212. try:
  213. sql = "DELETE FROM LOOKUP WHERE NODE = ?"
  214. self._cur.execute(sql, [node._id])
  215. except sqlite.DatabaseError as e: # pragma: no cover
  216. raise DatabaseException("SQLite: %s" % (e))
  217. self._commit()
  218. def _update_tag_lookup(self, node, tag_id):
  219. sql = "INSERT OR REPLACE INTO LOOKUP VALUES(?, ?)"
  220. params = [node._id, tag_id]
  221. try:
  222. self._cur.execute(sql, params)
  223. except sqlite.DatabaseError as e: # pragma: no cover
  224. raise DatabaseException("SQLite: %s" % (e))
  225. def _tagids(self, tags):
  226. ids = []
  227. sql = "SELECT ID FROM TAGS WHERE DATA LIKE ?"
  228. for tag in tags:
  229. try:
  230. if isinstance(tag, str):
  231. enc = CryptoEngine.get()
  232. tag = enc.encrypt(tag)
  233. self._cur.execute(sql, [tag])
  234. elif isinstance(tag, TagNew):
  235. self._cur.execute(sql, [tag._name.decode()+u'%'])
  236. else:
  237. self._cur.execute(sql, [tag.decode()+u'%'])
  238. values = self._cur.fetchall()
  239. if values: # tags already exist in the database
  240. ids.extend(list(itertools.chain(*values)))
  241. else:
  242. self._create_tag(tag)
  243. ids.append(self._cur.lastrowid)
  244. except sqlite.DatabaseError as e: # pragma: no cover
  245. raise DatabaseException("SQLite: %s" % (e))
  246. return ids
  247. def _setnodetags(self, node):
  248. ids = self._tagids(node.tags)
  249. for tagid in ids:
  250. self._update_tag_lookup(node, tagid)
  251. self._commit()
  252. def _checktags(self):
  253. try:
  254. sql = "DELETE FROM TAGS WHERE ID NOT IN (SELECT TAG FROM" \
  255. + " LOOKUP GROUP BY TAG)"
  256. self._cur.execute(sql)
  257. except sqlite.DatabaseError as e: # pragma: no cover
  258. raise DatabaseException("SQLite: %s" % (e))
  259. self._commit()
  260. def _checktables(self):
  261. """
  262. Check if the Pwman tables exist.
  263. TODO: This method should check the version of the
  264. database. If it finds an old format it should
  265. exis, and prompt the user to convert the database
  266. to the new version with a designated script.
  267. """
  268. self._cur.execute("PRAGMA TABLE_INFO(NODES)")
  269. if self._cur.fetchone() is None:
  270. # table doesn't exist, create it
  271. # SQLite does have constraints implemented at the moment
  272. # so datatype will just be a string
  273. self._cur.execute("CREATE TABLE NODES (ID INTEGER PRIMARY KEY"
  274. " AUTOINCREMENT,DATA BLOB NOT NULL)")
  275. self._cur.execute("CREATE TABLE TAGS"
  276. "(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
  277. "DATA BLOB NOT NULL UNIQUE)")
  278. self._cur.execute("CREATE TABLE LOOKUP"
  279. "(NODE INTEGER NOT NULL, TAG INTEGER NOT NULL,"
  280. " PRIMARY KEY(NODE, TAG))")
  281. self._cur.execute("CREATE TABLE KEY"
  282. "(THEKEY TEXT NOT NULL DEFAULT '')")
  283. self._cur.execute("INSERT INTO KEY VALUES('')")
  284. # create a table to hold DB version info
  285. self._cur.execute("CREATE TABLE DBVERSION"
  286. "(DBVERSION TEXT NOT NULL DEFAULT '%s')" %
  287. self.dbformat)
  288. self._cur.execute("INSERT INTO DBVERSION VALUES('%s')" %
  289. self.dbformat)
  290. try:
  291. self._con.commit()
  292. except DatabaseException as e: # pragma: no cover
  293. self._con.rollback()
  294. raise e
  295. def savekey(self, key):
  296. """
  297. This function is saving the key to table KEY.
  298. The key already arrives as an encrypted string.
  299. It is the same self._keycrypted from
  300. crypto py (check with id(self._keycrypted) and
  301. id(key) here.
  302. """
  303. sql = "UPDATE KEY SET THEKEY = ?"
  304. values = [key]
  305. self._cur.execute(sql, values)
  306. try:
  307. self._con.commit()
  308. except sqlite.DatabaseError as e: # pragma: no cover
  309. self._con.rollback()
  310. raise DatabaseException(
  311. "SQLite: Error saving key [%s]" % (e))
  312. def loadkey(self):
  313. """
  314. fetch the key to database. the key is also stored
  315. encrypted.
  316. """
  317. self._cur.execute("SELECT THEKEY FROM KEY")
  318. keyrow = self._cur.fetchone()
  319. if (keyrow[0] == ''):
  320. return None
  321. else:
  322. return keyrow[0]