sqlite.py 13 KB

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