c89f26307e7b169a6c249962776b2d6fa67f9a07
1 from straw
.defs
import STRAW_DATA_DIR
3 from pysqlite2
import dbapi2
as sqlite
6 DATABASE_FILE_NAME
= "data.db"
10 Provides an entry point to the database.
14 def __init__(self
, db_path
):
15 self
._connections
= {}
17 self
._db
_path
= db_path
21 f
= open(os
.path
.join(STRAW_DATA_DIR
, 'sql', 'create_01.sql'), 'r')
24 return sql
.split("--")
30 # Check if we need init.
31 # TODO: use smarter strategy maybe?
32 self
.query("SELECT COUNT(*) FROM feeds")
34 # DB seems not initialized.
52 print "DB init failed -- %s" % e
55 key
= threading
.currentThread()
57 if not self
._connections
.has_key(key
):
58 self
._connections
[key
] = sqlite
.connect(self
._db
_path
)
59 self
._connections
[key
].execute("PRAGMA cache_size = 20000;")
60 self
._connections
[key
].execute("PRAGMA synchronous = NORMAL;")
61 self
._connections
[key
].row_factory
= sqlite
.Row
63 return self
._connections
[key
]
66 key
= threading
.currentThread()
68 if not self
._txs
.has_key(key
):
72 key
= threading
.currentThread()
73 self
._connect
().commit()
74 self
._txs
[key
] = False
77 key
= threading
.currentThread()
78 return self
._txs
.has_key(key
) and self
._txs
[key
]
80 def query(self
, query
, params
= None):
83 cursor
= self
._connect
()
85 res
= cursor
.execute(query
, params
)
88 def insert(self
, table
, data
):
90 Inserts some data into the database.
92 @param table: a name of the table to insert to
93 @param data: a dictionary where keys are field names and values
94 are field values in the given table
101 cursor
= self
._connect
().cursor()
102 query
= "INSERT INTO %s (%s) VALUES (?%s)" % (table
, ", ".join(data
.keys()),
103 ", ?" * (len(data
.keys()) - 1))
106 cursor
.execute(query
, data
.values())
109 if not self
._in
_tx
():
112 return cursor
.lastrowid
114 def update(self
, table
, id, data
):
116 Updates single row identified by a primary key in the table.
118 @param table: a name of the table to do the update in
119 @param id: primary key of the item to update
120 @param data: a dictionary where keys are field names and values
121 are field values in the given table
125 return self
.update_with_where(table
, "WHERE id = %d" % id, data
)
127 def update_with_where(self
, table
, where_clause
, data
):
128 params
= data
.values()
129 cursor
= self
._connect
().cursor()
130 assignments
= ", ".join([("%s = ?" % field_name
) for field_name
in data
.keys()])
131 query
= "UPDATE %s SET %s %s" % (table
, assignments
, where_clause
)
133 cursor
.execute(query
, params
)
135 if not self
._in
_tx
():
138 return cursor
.lastrowid