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 result
= self
.query("SELECT COUNT(*) FROM feeds")
34 # DB seems not initialized.
48 print "DB init failed -- %s" % e
51 key
= threading
.currentThread()
53 if not self
._connections
.has_key(key
):
54 self
._connections
[key
] = sqlite
.connect(self
._db
_path
)
55 self
._connections
[key
].execute("PRAGMA cache_size = 20000;")
56 self
._connections
[key
].execute("PRAGMA synchronous = NORMAL;")
57 self
._connections
[key
].row_factory
= sqlite
.Row
59 return self
._connections
[key
]
62 key
= threading
.currentThread()
64 if not self
._txs
.has_key(key
):
68 self
._connect
().commit()
70 key
= threading
.currentThread()
71 self
._txs
[key
] = False
74 key
= threading
.currentThread()
75 return self
._txs
.has_key(key
) and self
._txs
[key
]
77 def query(self
, query
, params
= None):
80 cursor
= self
._connect
()
82 res
= cursor
.execute(query
, params
)
85 def insert(self
, table
, data
):
87 Inserts some data into the database.
89 @param table: a name of the table to insert to
90 @param data: a dictionary where keys are field names and values
91 are field values in the given table
98 cursor
= self
._connect
().cursor()
99 query
= "INSERT INTO %s (%s) VALUES (?%s)" % (table
, ", ".join(data
.keys()),
100 ", ?" * (len(data
.keys()) - 1))
103 cursor
.execute(query
, data
.values())
106 if not self
._in
_tx
():
109 return cursor
.lastrowid
111 def update(self
, table
, id, data
):
113 Updates single row identified by a primary key in the table.
115 @param table: a name of the table to do the update in
116 @param id: primary key of the item to update
117 @param data: a dictionary where keys are field names and values
118 are field values in the given table
122 params
= data
.values()
123 cursor
= self
._connect
().cursor()
124 assignments
= ", ".join([("%s = ?" % field_name
) for field_name
in data
.keys()])
125 query
= "UPDATE %s SET %s WHERE id = ?" % (table
, assignments
)
128 cursor
.execute(query
, params
)
130 if not self
._in
_tx
():
133 return cursor
.lastrowid