sqlite.py 13 KB

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