sqlite.py 12 KB

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