1 from pysqlite2
import dbapi2
as sqlite
4 DATABASE_FILE_NAME
= "data.db"
8 Provides an entry point to the database.
12 def __init__(self
, db_path
):
13 self
._connections
= {}
15 self
._db
_path
= db_path
19 f
= open('data/sql/create_01.sql', 'r')
22 return sql
.split("--")
28 # Check if we need init.
29 # TODO: use smarter strategy maybe?
30 result
= self
.query("SELECT COUNT(*) FROM feeds")
32 # DB seems not initialized.
46 print "DB init failed -- %s" % e
49 key
= threading
.currentThread()
51 if not self
._connections
.has_key(key
):
52 self
._connections
[key
] = sqlite
.connect(self
._db
_path
)
53 self
._connections
[key
].execute("PRAGMA cache_size = 20000;")
54 self
._connections
[key
].execute("PRAGMA synchronous = NORMAL;")
55 self
._connections
[key
].row_factory
= sqlite
.Row
57 return self
._connections
[key
]
60 key
= threading
.currentThread()
62 if not self
._txs
.has_key(key
):
66 self
._connect
().commit()
68 key
= threading
.currentThread()
69 self
._txs
[key
] = False
72 key
= threading
.currentThread()
73 return self
._txs
.has_key(key
) and self
._txs
[key
]
75 def query(self
, query
, params
= None):
78 cursor
= self
._connect
()
80 res
= cursor
.execute(query
, params
)
83 def insert(self
, table
, data
):
85 Inserts some data into the database.
87 @param table: a name of the table to insert to
88 @param data: a dictionary where keys are field names and values
89 are field values in the given table
96 cursor
= self
._connect
().cursor()
97 query
= "INSERT INTO %s (%s) VALUES (?%s)" % (table
, ", ".join(data
.keys()),
98 ", ?" * (len(data
.keys()) - 1))
101 cursor
.execute(query
, data
.values())
104 if not self
._in
_tx
():
107 return cursor
.lastrowid
109 def update(self
, table
, id, data
):
111 Updates single row identified by a primary key in the table.
113 @param table: a name of the table to do the update in
114 @param id: primary key of the item to update
115 @param data: a dictionary where keys are field names and values
116 are field values in the given table
120 params
= data
.values()
121 cursor
= self
._connect
().cursor()
122 assignments
= ", ".join([("%s = ?" % field_name
) for field_name
in data
.keys()])
123 query
= "UPDATE %s SET %s WHERE id = ?" % (table
, assignments
)
126 cursor
.execute(query
, params
)
128 if not self
._in
_tx
():
131 return cursor
.lastrowid