added update_filed function
[meabook] / database / SQLite.py
1 import os
2 import sqlite3
3
4 DATABASE_NAME = 'contacts.db'
5
6
7 class SQLite:
8     def __init__(self, basedir):
9         self._path = os.path.join(basedir, DATABASE_NAME)
10         self.conn = None
11         if not os.path.exists(self._path):
12             self.new()
13         else:
14             self.conn = sqlite3.connect(self._path)
15
16     def new(self):
17         """Creates new databse."""
18
19         self.conn = sqlite3.connect(self._path)
20         self.conn.execute("""CREATE TABLE data (user_id int, field_id int, \
21             value str)""")
22         self.conn.execute("""CREATE TABLE field (id int primary key, name str)""")
23         self.conn.execute("""CREATE TABLE relation (data_id int, \
24             struct_id int)""")
25         self.conn.execute("""CREATE TABLE struct (id int, name str, \
26             parent_id int)""")
27         self.conn.commit()
28
29     def close(self):
30         """Closes connection with database."""
31
32         self.conn.commit()
33         self.conn.close()
34
35     def update_field(self, fname):
36         """Adds new field to database."""
37
38         fields = self.conn.execute("""SELECT name from field""").fetchall()
39         if not fname in fields:
40             self.conn.execute("""INSERT INTO field values((SELECT max(id) 
41             FROM field)+1, ?)""", (fname,))
42
43
44 if __name__ == "__main__":
45     db = SQLite('/tmp/')
46     db.update_field('test')
47     db.close()
48
49