-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathsqlite.py
279 lines (227 loc) · 7.97 KB
/
sqlite.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# -*- coding: utf-8 -*-
import os
import sqlite3
import logging
from appdirs import user_data_dir
from .interfaces import StoreInterface
log = logging.getLogger(__name__)
timeformat = "%Y%m%d-%H%M%S"
class SQLiteFile:
"""This class ensures that the user's data is stored in its OS
preotected user directory:
**OSX:**
* `~/Library/Application Support/<AppName>`
**Windows:**
* `C:\\Documents and Settings\\<User>\\Application Data\\Local Settings\\<AppAuthor>\\<AppName>`
* `C:\\Documents and Settings\\<User>\\Application Data\\<AppAuthor>\\<AppName>`
**Linux:**
* `~/.local/share/<AppName>`
Furthermore, it offers an interface to generated backups
in the `backups/` directory every now and then.
.. note:: The file name can be overwritten when providing a keyword
argument ``profile``.
"""
def __init__(self, *args, **kwargs):
appauthor = "Fabian Schuh"
appname = kwargs.get("appname", "graphene")
data_dir = kwargs.get("data_dir", user_data_dir(appname, appauthor))
if "profile" in kwargs:
self.storageDatabase = "{}.sqlite".format(kwargs["profile"])
else:
self.storageDatabase = "{}.sqlite".format(appname)
self.sqlite_file = os.path.join(data_dir, self.storageDatabase)
""" Ensure that the directory in which the data is stored
exists
"""
if os.path.isdir(data_dir): # pragma: no cover
return
else: # pragma: no cover
os.makedirs(data_dir)
class SQLiteCommon(object):
"""This class abstracts away common sqlite3 operations.
This class should not be used directly.
When inheriting from this class, the following instance members must
be defined:
* ``sqlite_file``: Path to the SQLite Database file
"""
def sql_fetchone(self, query):
connection = sqlite3.connect(self.sqlite_file)
try:
cursor = connection.cursor()
cursor.execute(*query)
result = cursor.fetchone()
finally:
connection.close()
return result
def sql_fetchall(self, query):
connection = sqlite3.connect(self.sqlite_file)
try:
cursor = connection.cursor()
cursor.execute(*query)
results = cursor.fetchall()
finally:
connection.close()
return results
def sql_execute(self, query, lastid=False):
connection = sqlite3.connect(self.sqlite_file)
try:
cursor = connection.cursor()
cursor.execute(*query)
connection.commit()
except Exception:
connection.close()
raise
ret = None
try:
if lastid:
cursor = connection.cursor()
cursor.execute("SELECT last_insert_rowid();")
ret = cursor.fetchone()[0]
finally:
connection.close()
return ret
class SQLiteStore(SQLiteFile, SQLiteCommon, StoreInterface):
"""The SQLiteStore deals with the sqlite3 part of storing data into a
database file.
.. note:: This module is limited to two columns and merely stores
key/value pairs into the sqlite database
On first launch, the database file as well as the tables are created
automatically.
When inheriting from this class, the following three class members must
be defined:
* ``__tablename__``: Name of the table
* ``__key__``: Name of the key column
* ``__value__``: Name of the value column
"""
#:
__tablename__ = None
__key__ = None
__value__ = None
def __init__(self, *args, **kwargs):
#: Storage
SQLiteFile.__init__(self, *args, **kwargs)
StoreInterface.__init__(self, *args, **kwargs)
if self.__tablename__ is None or self.__key__ is None or self.__value__ is None:
raise ValueError("Values missing for tablename, key, or value!")
if not self.exists(): # pragma: no cover
self.create()
def _haveKey(self, key):
"""Is the key `key` available?"""
query = (
"SELECT {} FROM {} WHERE {}=?".format(
self.__value__, self.__tablename__, self.__key__
),
(key,),
)
return True if self.sql_fetchone(query) else False
def __setitem__(self, key, value):
"""Sets an item in the store
:param str key: Key
:param str value: Value
"""
if self._haveKey(key):
query = (
"UPDATE {} SET {}=? WHERE {}=?".format(
self.__tablename__, self.__value__, self.__key__
),
(value, key),
)
else:
query = (
"INSERT INTO {} ({}, {}) VALUES (?, ?)".format(
self.__tablename__, self.__key__, self.__value__
),
(key, value),
)
self.sql_execute(query)
def __getitem__(self, key):
"""Gets an item from the store as if it was a dictionary
:param str value: Value
"""
query = (
"SELECT {} FROM {} WHERE {}=?".format(
self.__value__, self.__tablename__, self.__key__
),
(key,),
)
result = self.sql_fetchone(query)
if result:
return result[0]
else:
if key in self.defaults:
return self.defaults[key]
else:
return None
def __iter__(self):
"""Iterates through the store"""
return iter(self.keys())
def keys(self):
query = ("SELECT {} from {}".format(self.__key__, self.__tablename__),)
return [x[0] for x in self.sql_fetchall(query)]
def __len__(self):
"""return lenght of store"""
query = ("SELECT id from {}".format(self.__tablename__),)
return len(self.sql_fetchall(query))
def __contains__(self, key):
"""Tests if a key is contained in the store.
May test againsts self.defaults
:param str value: Value
"""
if self._haveKey(key) or key in self.defaults:
return True
else:
return False
def items(self):
"""returns all items off the store as tuples"""
query = (
"SELECT {}, {} from {}".format(
self.__key__, self.__value__, self.__tablename__
),
)
r = []
for key, value in self.sql_fetchall(query):
r.append((key, value))
return r
def get(self, key, default=None):
"""Return the key if exists or a default value
:param str value: Value
:param str default: Default value if key not present
"""
if key in self:
return self.__getitem__(key)
else:
return default
# Specific for this library
def delete(self, key):
"""Delete a key from the store
:param str value: Value
"""
query = (
"DELETE FROM {} WHERE {}=?".format(self.__tablename__, self.__key__),
(key,),
)
self.sql_execute(query)
def wipe(self):
"""Wipe the store"""
query = ("DELETE FROM {}".format(self.__tablename__),)
self.sql_execute(query)
def exists(self):
"""Check if the database table exists"""
query = (
"SELECT name FROM sqlite_master " + "WHERE type='table' AND name=?",
(self.__tablename__,),
)
return True if self.sql_fetchone(query) else False
def create(self): # pragma: no cover
"""Create the new table in the SQLite database"""
query = (
(
"""
CREATE TABLE {} (
id INTEGER PRIMARY KEY AUTOINCREMENT,
{} STRING(256),
{} STRING(256)
)"""
).format(self.__tablename__, self.__key__, self.__value__),
)
self.sql_execute(query)