sqlite.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  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. #============================================================================
  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 Node
  25. from pwman.data.tags import Tag
  26. import sys
  27. if sys.version_info > (2, 5):
  28. import sqlite3 as sqlite
  29. else:
  30. try:
  31. from pysqlite2 import dbapi2 as sqlite
  32. except ImportError:
  33. raise DatabaseException("python-sqlite2 not installed")
  34. import pwman.util.config as config
  35. import cPickle
  36. def check_db_version():
  37. """
  38. check the data base version query the right table
  39. """
  40. try:
  41. filename = config.get_value('Database', 'filename')
  42. con = sqlite.connect(filename)
  43. cur = con.cursor()
  44. cur.execute("PRAGMA TABLE_INFO(DBVERSION)")
  45. row = cur.fetchone()
  46. if row is None:
  47. return "0.3"
  48. try:
  49. return row[-2]
  50. except IndexError:
  51. raise DatabaseException("Something seems fishy with the DB")
  52. except sqlite.DatabaseError, e:
  53. raise DatabaseException("SQLite: %s" % (e))
  54. class SQLiteDatabaseNewForm(Database):
  55. """SQLite Database implementation"""
  56. def __init__(self):
  57. """Initialise SQLitePwmanDatabase instance."""
  58. Database.__init__(self)
  59. try:
  60. self._filename = config.get_value('Database', 'filename')
  61. except KeyError, e:
  62. raise DatabaseException(
  63. "SQLite: missing parameter [%s]" % (e))
  64. def _open(self):
  65. try:
  66. self._con = sqlite.connect(self._filename)
  67. self._cur = self._con.cursor()
  68. self._checktables()
  69. except sqlite.DatabaseError, e:
  70. raise DatabaseException("SQLite: %s" % (e))
  71. def close(self):
  72. self._cur.close()
  73. self._con.close()
  74. def listtags(self, alltags=False):
  75. sql = ''
  76. params = []
  77. if len(self._filtertags) == 0 or alltags:
  78. sql = "SELECT DATA FROM TAGS ORDER BY DATA ASC"
  79. else:
  80. sql = ("SELECT TAGS.DATA FROM LOOKUP"
  81. + " INNER JOIN TAGS ON LOOKUP.TAG = TAGS.ID"
  82. + " WHERE NODE IN (")
  83. first = True
  84. # if using the command filter, the code crashes ...
  85. #
  86. for t in self._filtertags:
  87. if not first:
  88. sql += " INTERSECT "
  89. else:
  90. first = False
  91. sql += ("SELECT NODE FROM LOOKUP LEFT JOIN TAGS ON TAG = "
  92. + " TAGS.ID WHERE TAGS.DATA = ?")
  93. params.append(t.get_name())
  94. sql += ") EXCEPT SELECT DATA FROM TAGS WHERE "
  95. first = True
  96. for t in self._filtertags:
  97. if not first:
  98. sql += " OR "
  99. else:
  100. first = False
  101. sql += "TAGS.DATA = ?"
  102. params.append(t)
  103. try:
  104. self._cur.execute(sql, params)
  105. tags = []
  106. row = self._cur.fetchone()
  107. while row is not None:
  108. tagstring = str(row[0])
  109. m = re.search('S\"S\'(.+?)\'', tagstring)
  110. if m:
  111. found = m.group(1)
  112. tags.append(Tag(found))
  113. row = self._cur.fetchone()
  114. return tags
  115. except sqlite.DatabaseError, e:
  116. raise DatabaseException("SQLite: %s" % (e))
  117. def parse_node_string(self, string):
  118. nodestring = string.split("##")
  119. keyvals = {}
  120. for pair in nodestring[:-1]:
  121. key, val = pair.split(":")
  122. keyvals[key.lstrip('##')] = val
  123. tags = nodestring[-1]
  124. tags = tags.lstrip("tags:")
  125. tags = tags.split("tag:")
  126. taginsts = []
  127. for tag in tags:
  128. _Tag = tag.rstrip("**endtag**")
  129. Tag = (_Tag)
  130. taginsts.append(Tag)
  131. return keyvals, taginsts
  132. def getnodes(self, ids):
  133. """
  134. object should always be: (ipwman.data.nodes
  135. """
  136. nodes = []
  137. for i in ids:
  138. sql = "SELECT DATA FROM NODES WHERE ID = ?"
  139. # try:
  140. self._cur.execute(sql, [i])
  141. row = self._cur.fetchone()
  142. if row is not None:
  143. nodestring = str(row[0])
  144. # if not nodestring.startswith("(ipwman.data.nodes"):
  145. # raise DatabaseException(
  146. #"Tried to load foreign object from database," \
  147. #+ " this looks fishy in here...")
  148. nodeargs, tags = self.parse_node_string(nodestring)
  149. node = Node(**nodeargs)
  150. node.set_tags(tags)
  151. node.set_id(i)
  152. nodes.append(node)
  153. # except sqlite.DatabaseError, e:
  154. # raise DatabaseException("SQLite: %s" % (e))
  155. return nodes
  156. def editnode(self, id, node):
  157. try:
  158. sql = "UPDATE NODES SET DATA = ? WHERE ID = ?"
  159. self._cur.execute(sql, [node.dump_edit_to_db()[0], id])
  160. except sqlite.DatabaseError, e:
  161. raise DatabaseException("SQLite: %s" % (e))
  162. self._setnodetags(node)
  163. self._checktags()
  164. self._commit()
  165. def addnodes(self, nodes):
  166. """
  167. This method injects the data as PWMAN object using cPickle.
  168. To make pwman more secure, either this method has to replaced.
  169. Or whenever stuff is read from the database, there must be a
  170. security check that it contains the correct objects!
  171. Nodes passed to this methos are instances!
  172. """
  173. for n in nodes:
  174. sql = "INSERT INTO NODES(DATA) VALUES(?)"
  175. # if not isinstance(n, Node): raise DatabaseException(
  176. # "Tried to insert foreign object into database [%s]", n)
  177. value = n.dump_to_db()
  178. try:
  179. self._cur.execute(sql, value)
  180. except sqlite.DatabaseError, e:
  181. raise DatabaseException("SQLite: %s" % (e))
  182. idx = self._cur.lastrowid
  183. n.set_id(idx)
  184. self._setnodetags(n)
  185. self._commit()
  186. def removenodes(self, nodes):
  187. for n in nodes:
  188. # if not isinstance(n, Node): raise DatabaseException(
  189. # "Tried to delete foreign object from database [%s]", n)
  190. try:
  191. sql = "DELETE FROM NODES WHERE ID = ?"
  192. self._cur.execute(sql, [n.get_id()])
  193. except sqlite.DatabaseError, e:
  194. raise DatabaseException("SQLite: %s" % (e))
  195. self._deletenodetags(n)
  196. self._checktags()
  197. self._commit()
  198. def listnodes(self):
  199. sql = ''
  200. params = []
  201. if len(self._filtertags) == 0:
  202. sql = "SELECT ID FROM NODES ORDER BY ID ASC"
  203. else:
  204. first = True
  205. for t in self._filtertags:
  206. if not first:
  207. sql += " INTERSECT "
  208. else:
  209. first = False
  210. sql += ("SELECT NODE FROM LOOKUP LEFT JOIN TAGS ON TAG = "
  211. " TAGS.ID WHERE TAGS.DATA = ? ")
  212. params.append(t.get_name())
  213. try:
  214. self._cur.execute(sql, params)
  215. ids = []
  216. row = self._cur.fetchone()
  217. while row is not None:
  218. ids.append(row[0])
  219. row = self._cur.fetchone()
  220. return ids
  221. except sqlite.DatabaseError, e:
  222. raise DatabaseException("SQLite: %s" % (e))
  223. def _commit(self):
  224. try:
  225. self._con.commit()
  226. except sqlite.DatabaseError, e:
  227. self._con.rollback()
  228. raise DatabaseException(
  229. "SQLite: Error commiting data to db [%s]" % (e))
  230. def _tagids(self, tags):
  231. ids = []
  232. for tag in tags:
  233. sql = "SELECT ID FROM TAGS WHERE DATA = ?"
  234. # if not isinstance(t, Tag): raise DatabaseException(
  235. # "Tried to insert foreign object into database [%s]", t)
  236. try:
  237. if isinstance(tag, str):
  238. self._cur.execute(sql, [tag])
  239. else:
  240. self._cur.execute(sql, [tag.get_name()])
  241. row = self._cur.fetchone()
  242. if (row is not None):
  243. ids.append(row[0])
  244. else:
  245. sql = "INSERT INTO TAGS(DATA) VALUES(?)"
  246. if isinstance(tag, str):
  247. self._cur.execute(sql, [tag])
  248. else:
  249. self._cur.execute(sql, [tag.get_name()])
  250. ids.append(self._cur.lastrowid)
  251. except sqlite.DatabaseError, e:
  252. raise DatabaseException("SQLite: %s" % (e))
  253. return ids
  254. def _deletenodetags(self, node):
  255. try:
  256. sql = "DELETE FROM LOOKUP WHERE NODE = ?"
  257. self._cur.execute(sql, [node.get_id()])
  258. except sqlite.DatabaseError, e:
  259. raise DatabaseException("SQLite: %s" % (e))
  260. self._commit()
  261. def _setnodetags(self, node):
  262. self._deletenodetags(node)
  263. ids = self._tagids(node.get_tags())
  264. for i in ids:
  265. sql = "INSERT OR REPLACE INTO LOOKUP VALUES(?, ?)"
  266. params = [node.get_id(), i]
  267. try:
  268. self._cur.execute(sql, params)
  269. except sqlite.DatabaseError, e:
  270. raise DatabaseException("SQLite: %s" % (e))
  271. self._commit()
  272. def _checktags(self):
  273. try:
  274. sql = "DELETE FROM TAGS WHERE ID NOT IN (SELECT TAG FROM" \
  275. + " LOOKUP GROUP BY TAG)"
  276. self._cur.execute(sql)
  277. except sqlite.DatabaseError, e:
  278. raise DatabaseException("SQLite: %s" % (e))
  279. self._commit()
  280. def _checktables(self):
  281. """
  282. Check if the Pwman tables exist.
  283. TODO: This method should check the version of the
  284. database. If it finds an old format it should
  285. exis, and prompt the user to convert the database
  286. to the new version with a designated script.
  287. """
  288. self._cur.execute("PRAGMA TABLE_INFO(NODES)")
  289. if (self._cur.fetchone() is None):
  290. # table doesn't exist, create it
  291. # SQLite does have constraints implemented at the moment
  292. # so datatype will just be a string
  293. self._cur.execute("CREATE TABLE NODES (ID INTEGER PRIMARY KEY"
  294. + " AUTOINCREMENT,DATA BLOB NOT NULL)")
  295. self._cur.execute("CREATE TABLE TAGS"
  296. + "(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
  297. + "DATA BLOB NOT NULL UNIQUE)")
  298. self._cur.execute("CREATE TABLE LOOKUP"
  299. + "(NODE INTEGER NOT NULL, TAG INTEGER NOT NULL,"
  300. + " PRIMARY KEY(NODE, TAG))")
  301. self._cur.execute("CREATE TABLE KEY"
  302. + "(THEKEY TEXT NOT NULL DEFAULT '')")
  303. self._cur.execute("INSERT INTO KEY VALUES('')")
  304. # create a table to hold DB version info
  305. self._cur.execute("CREATE TABLE DBVERSION"
  306. + "(DBVERSION TEXT NOT NULL DEFAULT '0.4')")
  307. self._cur.execute("INSERT INTO DBVERSION VALUES('0.4')")
  308. try:
  309. self._con.commit()
  310. except DatabaseException, e:
  311. self._con.rollback()
  312. raise e
  313. def savekey(self, key):
  314. """
  315. This function is saving the key to table KEY.
  316. The key already arrives as an encrypted string.
  317. It is the same self._keycrypted from
  318. crypto py (check with id(self._keycrypted) and
  319. id(key) here.
  320. """
  321. sql = "UPDATE KEY SET THEKEY = ?"
  322. values = [key]
  323. self._cur.execute(sql, values)
  324. try:
  325. self._con.commit()
  326. except sqlite.DatabaseError, e:
  327. self._con.rollback()
  328. raise DatabaseException(
  329. "SQLite: Error saving key [%s]" % (e))
  330. def loadkey(self):
  331. """
  332. fetch the key to database. the key is also stored
  333. encrypted.
  334. """
  335. self._cur.execute("SELECT THEKEY FROM KEY")
  336. keyrow = self._cur.fetchone()
  337. if (keyrow[0] == ''):
  338. return None
  339. else:
  340. return keyrow[0]
  341. class SQLiteDatabase(Database):
  342. """SQLite Database implementation"""
  343. def __init__(self):
  344. """Initialise SQLitePwmanDatabase instance."""
  345. Database.__init__(self)
  346. try:
  347. self._filename = config.get_value('Database', 'filename')
  348. except KeyError, e:
  349. raise DatabaseException(
  350. "SQLite: missing parameter [%s]" % (e))
  351. def _open(self):
  352. try:
  353. self._con = sqlite.connect(self._filename)
  354. self._cur = self._con.cursor()
  355. self._checktables()
  356. except sqlite.DatabaseError, e:
  357. raise DatabaseException("SQLite: %s" % (e))
  358. def close(self):
  359. self._cur.close()
  360. self._con.close()
  361. def listtags(self, all=False):
  362. sql = ''
  363. params = []
  364. if len(self._filtertags) == 0 or all:
  365. sql = "SELECT DATA FROM TAGS ORDER BY DATA ASC"
  366. else:
  367. sql = ("SELECT TAGS.DATA FROM LOOKUP"
  368. +" INNER JOIN TAGS ON LOOKUP.TAG = TAGS.ID"
  369. +" WHERE NODE IN (")
  370. first = True
  371. for t in self._filtertags:
  372. if not first:
  373. sql += " INTERSECT "
  374. else:
  375. first = False
  376. sql += ("SELECT NODE FROM LOOKUP LEFT JOIN TAGS ON TAG = TAGS.ID "
  377. + " WHERE TAGS.DATA = ?")
  378. params.append(cPickle.dumps(t))
  379. sql += ") EXCEPT SELECT DATA FROM TAGS WHERE "
  380. first = True
  381. for t in self._filtertags:
  382. if not first:
  383. sql += " OR "
  384. else:
  385. first = False
  386. sql += "TAGS.DATA = ?"
  387. params.append(cPickle.dumps(t))
  388. try:
  389. self._cur.execute(sql, params)
  390. tags = []
  391. row = self._cur.fetchone()
  392. while (row != None):
  393. tag = cPickle.loads(str(row[0]))
  394. tags.append(tag)
  395. row = self._cur.fetchone()
  396. return tags
  397. except sqlite.DatabaseError, e:
  398. raise DatabaseException("SQLite: %s" % (e))
  399. def getnodes(self, ids):
  400. nodes = []
  401. for i in ids:
  402. sql = "SELECT DATA FROM NODES WHERE ID = ?"
  403. try:
  404. self._cur.execute(sql, [i])
  405. row = self._cur.fetchone()
  406. if row != None:
  407. node = cPickle.loads(str(row[0]))
  408. node.set_id(i)
  409. nodes.append(node)
  410. except sqlite.DatabaseError, e:
  411. raise DatabaseException("SQLite: %s" % (e))
  412. return nodes
  413. def editnode(self, id, node):
  414. if not isinstance(node, Node): raise DatabaseException(
  415. "Tried to insert foreign object into database [%s]" % node)
  416. try:
  417. sql = "UPDATE NODES SET DATA = ? WHERE ID = ?";
  418. self._cur.execute(sql, [cPickle.dumps(node), id])
  419. except sqlite.DatabaseError, e:
  420. raise DatabaseException("SQLite: %s" % (e))
  421. self._setnodetags(node)
  422. self._checktags()
  423. self._commit()
  424. def addnodes(self, nodes):
  425. for n in nodes:
  426. sql = "INSERT INTO NODES(DATA) VALUES(?)"
  427. if not isinstance(n, Node): raise DatabaseException(
  428. "Tried to insert foreign object into database [%s]", n)
  429. value = cPickle.dumps(n)
  430. try:
  431. self._cur.execute(sql, [value])
  432. except sqlite.DatabaseError, e:
  433. raise DatabaseException("SQLite: %s" % (e))
  434. id = self._cur.lastrowid
  435. n.set_id(id)
  436. self._setnodetags(n)
  437. self._commit()
  438. def removenodes(self, nodes):
  439. for n in nodes:
  440. if not isinstance(n, Node): raise DatabaseException(
  441. "Tried to delete foreign object from database [%s]", n)
  442. try:
  443. sql = "DELETE FROM NODES WHERE ID = ?";
  444. self._cur.execute(sql, [n.get_id()])
  445. except sqlite.DatabaseError, e:
  446. raise DatabaseException("SQLite: %s" % (e))
  447. self._deletenodetags(n)
  448. self._checktags()
  449. self._commit()
  450. def listnodes(self):
  451. sql = ''
  452. params = []
  453. if len(self._filtertags) == 0:
  454. sql = "SELECT ID FROM NODES ORDER BY ID ASC"
  455. else:
  456. first = True
  457. for t in self._filtertags:
  458. if not first:
  459. sql += " INTERSECT "
  460. else:
  461. first = False
  462. sql += ("SELECT NODE FROM LOOKUP LEFT JOIN TAGS ON TAG = TAGS.ID"
  463. + " WHERE TAGS.DATA = ? ")
  464. params.append(cPickle.dumps(t))
  465. try:
  466. self._cur.execute(sql, params)
  467. ids = []
  468. row = self._cur.fetchone()
  469. while (row != None):
  470. ids.append(row[0])
  471. row = self._cur.fetchone()
  472. return ids
  473. except sqlite.DatabaseError, e:
  474. raise DatabaseException("SQLite: %s" % (e))
  475. def _commit(self):
  476. try:
  477. self._con.commit()
  478. except sqlite.DatabaseError, e:
  479. self._con.rollback()
  480. raise DatabaseException(
  481. "SQLite: Error commiting data to db [%s]" % (e))
  482. def _tagids(self, tags):
  483. ids = []
  484. for t in tags:
  485. sql = "SELECT ID FROM TAGS WHERE DATA = ?"
  486. if not isinstance(t, Tag): raise DatabaseException(
  487. "Tried to insert foreign object into database [%s]", t)
  488. data = cPickle.dumps(t)
  489. try:
  490. self._cur.execute(sql, [data])
  491. row = self._cur.fetchone()
  492. if (row != None):
  493. ids.append(row[0])
  494. else:
  495. sql = "INSERT INTO TAGS(DATA) VALUES(?)"
  496. self._cur.execute(sql, [data])
  497. ids.append(self._cur.lastrowid)
  498. except sqlite.DatabaseError, e:
  499. raise DatabaseException("SQLite: %s" % (e))
  500. return ids
  501. def _deletenodetags(self, node):
  502. try:
  503. sql = "DELETE FROM LOOKUP WHERE NODE = ?"
  504. self._cur.execute(sql, [node.get_id()])
  505. except sqlite.DatabaseError, e:
  506. raise DatabaseException("SQLite: %s" % (e))
  507. self._commit()
  508. def _setnodetags(self, node):
  509. self._deletenodetags(node)
  510. ids = self._tagids(node.get_tags())
  511. for i in ids:
  512. sql = "INSERT OR REPLACE INTO LOOKUP VALUES(?, ?)"
  513. params = [node.get_id(), i]
  514. try:
  515. self._cur.execute(sql, params)
  516. except sqlite.DatabaseError, e:
  517. raise DatabaseException("SQLite: %s" % (e))
  518. self._commit()
  519. def _checktags(self):
  520. try:
  521. sql = "DELETE FROM TAGS WHERE ID NOT IN (SELECT TAG FROM LOOKUP GROUP BY TAG)"
  522. self._cur.execute(sql)
  523. except sqlite.DatabaseError, e:
  524. raise DatabaseException("SQLite: %s" % (e))
  525. self._commit()
  526. def _checktables(self):
  527. """ Check if the Pwman tables exist """
  528. self._cur.execute("PRAGMA TABLE_INFO(NODES)")
  529. if (self._cur.fetchone() == None):
  530. # table doesn't exist, create it
  531. # SQLite does have constraints implemented at the moment
  532. # so datatype will just be a string
  533. self._cur.execute("CREATE TABLE NODES"
  534. + "(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
  535. + "DATA BLOB NOT NULL)")
  536. self._cur.execute("CREATE TABLE TAGS"
  537. + "(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
  538. + "DATA BLOB NOT NULL UNIQUE)")
  539. self._cur.execute("CREATE TABLE LOOKUP"
  540. + "(NODE INTEGER NOT NULL, TAG INTEGER NOT NULL,"
  541. + " PRIMARY KEY(NODE, TAG))")
  542. self._cur.execute("CREATE TABLE KEY"
  543. + "(THEKEY TEXT NOT NULL DEFAULT '')");
  544. self._cur.execute("INSERT INTO KEY VALUES('')");
  545. try:
  546. self._con.commit()
  547. except DatabaseError, e:
  548. self._con.rollback()
  549. raise e
  550. def savekey(self, key):
  551. sql = "UPDATE KEY SET THEKEY = ?"
  552. values = [key]
  553. self._cur.execute(sql, values)
  554. try:
  555. self._con.commit()
  556. except sqlite.DatabaseError, e:
  557. self._con.rollback()
  558. raise DatabaseException(
  559. "SQLite: Error saving key [%s]" % (e))
  560. def loadkey(self):
  561. """
  562. fetch the key to database. the key is also stored
  563. encrypted.
  564. """
  565. self._cur.execute("SELECT THEKEY FROM KEY");
  566. keyrow = self._cur.fetchone()
  567. if (keyrow[0] == ''):
  568. return None
  569. else:
  570. return keyrow[0]