sqlthon 0.0.14__tar.gz → 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {sqlthon-0.0.14 → sqlthon-0.1.0}/PKG-INFO +1 -1
- {sqlthon-0.0.14 → sqlthon-0.1.0}/pyproject.toml +1 -1
- {sqlthon-0.0.14 → sqlthon-0.1.0}/src/sqlthon/__init__.py +1 -1
- sqlthon-0.1.0/src/sqlthon/core.py +542 -0
- {sqlthon-0.0.14 → sqlthon-0.1.0}/src/sqlthon.egg-info/PKG-INFO +1 -1
- sqlthon-0.0.14/src/sqlthon/core.py +0 -334
- {sqlthon-0.0.14 → sqlthon-0.1.0}/README.md +0 -0
- {sqlthon-0.0.14 → sqlthon-0.1.0}/setup.cfg +0 -0
- {sqlthon-0.0.14 → sqlthon-0.1.0}/src/sqlthon/keywords.py +0 -0
- {sqlthon-0.0.14 → sqlthon-0.1.0}/src/sqlthon.egg-info/SOURCES.txt +0 -0
- {sqlthon-0.0.14 → sqlthon-0.1.0}/src/sqlthon.egg-info/dependency_links.txt +0 -0
- {sqlthon-0.0.14 → sqlthon-0.1.0}/src/sqlthon.egg-info/top_level.txt +0 -0
|
@@ -15,7 +15,7 @@ Channel: https://ble.ir/saums_channel
|
|
|
15
15
|
from .core import Connect, Field
|
|
16
16
|
|
|
17
17
|
__all__ = ['Connect', 'Field']
|
|
18
|
-
__version__ = '0.0
|
|
18
|
+
__version__ = '0.1.0'
|
|
19
19
|
__author__ = "SAUMS"
|
|
20
20
|
__email__ = "saums1391@gmail.com"
|
|
21
21
|
__description__ = "Operate With SQLite3 Buy Simple"
|
|
@@ -0,0 +1,542 @@
|
|
|
1
|
+
class Field:
|
|
2
|
+
__slots__ = ("name",)
|
|
3
|
+
def __init__(self, name):
|
|
4
|
+
_analysis_code(name)
|
|
5
|
+
self.name = name
|
|
6
|
+
|
|
7
|
+
def __gt__(self, value): return _Expression(self, ">", value)
|
|
8
|
+
def __lt__(self, value): return _Expression(self, "<", value)
|
|
9
|
+
def __ge__(self, value): return _Expression(self, ">=", value)
|
|
10
|
+
def __le__(self, value): return _Expression(self, "<=", value)
|
|
11
|
+
def __eq__(self, value): return _Expression(self, "=", value)
|
|
12
|
+
def __ne__(self, value): return _Expression(self, "!=", value)
|
|
13
|
+
def __invert__(self): return _Expression(self, "NOT", None)
|
|
14
|
+
def not_like(self, value): return _Expression(self, "NOT LIKE", value)
|
|
15
|
+
def like(self, value):
|
|
16
|
+
return _Expression(self, "LIKE", value)
|
|
17
|
+
def startswith(self, value):
|
|
18
|
+
return _Expression(self, "LIKE", f"{value}%")
|
|
19
|
+
def endswith(self, value):
|
|
20
|
+
return _Expression(self, "LIKE", f"%{value}")
|
|
21
|
+
def contains(self, value):
|
|
22
|
+
return _Expression(self, "LIKE", f"%{value}%")
|
|
23
|
+
def in_(self, value):
|
|
24
|
+
return _Expression(self, "IN", value)
|
|
25
|
+
def not_in(self, value):
|
|
26
|
+
return _Expression(self, "NOT IN", value)
|
|
27
|
+
def between(self, value):
|
|
28
|
+
return _Expression(self, "BETWEEN", value)
|
|
29
|
+
def is_null(self):
|
|
30
|
+
return _Expression(self, "IS NULL", None)
|
|
31
|
+
def is_not_null(self):
|
|
32
|
+
return _Expression(self, "IS NOT NULL", None)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class _Expression:
|
|
36
|
+
__slots__ = ("left", "op", "right")
|
|
37
|
+
def __init__(self, left, op, right):
|
|
38
|
+
self.left = left
|
|
39
|
+
self.op = op
|
|
40
|
+
self.right = right
|
|
41
|
+
|
|
42
|
+
def __and__(self, other):
|
|
43
|
+
return _Expression(self, "AND", other)
|
|
44
|
+
def __or__(self, other):
|
|
45
|
+
return _Expression(self, "OR", other)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class _Aggregate:
|
|
49
|
+
__slots__ = ("func", "column")
|
|
50
|
+
def __init__(self, func, column="*"):
|
|
51
|
+
if not column == "*":
|
|
52
|
+
_analysis_code(column)
|
|
53
|
+
self.func = func
|
|
54
|
+
self.column = column
|
|
55
|
+
|
|
56
|
+
def __gt__(self, value): return _Expression(self, ">", value)
|
|
57
|
+
def __lt__(self, value): return _Expression(self, "<", value)
|
|
58
|
+
def __ge__(self, value): return _Expression(self, ">=", value)
|
|
59
|
+
def __le__(self, value): return _Expression(self, "<=", value)
|
|
60
|
+
def __eq__(self, value): return _Expression(self, "=", value)
|
|
61
|
+
def __ne__(self, value): return _Expression(self, "!=", value)
|
|
62
|
+
|
|
63
|
+
def __str__(self):
|
|
64
|
+
return f"{self.func}({self.column})"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _compile(expr):
|
|
68
|
+
if isinstance(expr.left, _Expression) or isinstance(expr.right, _Expression):
|
|
69
|
+
left_sql, left_params = _compile(expr.left)
|
|
70
|
+
right_sql, right_params = _compile(expr.right)
|
|
71
|
+
sql = f"({left_sql}) {expr.op} ({right_sql})"
|
|
72
|
+
params = left_params + right_params
|
|
73
|
+
return sql, params
|
|
74
|
+
elif expr.op in ("IN", "NOT IN"):
|
|
75
|
+
placeholders = ", ".join(["?"] * len(expr.right))
|
|
76
|
+
sql = f'"{expr.left.name}" {expr.op} ({placeholders})'
|
|
77
|
+
params = tuple(expr.right)
|
|
78
|
+
return sql, params
|
|
79
|
+
elif expr.op == "BETWEEN":
|
|
80
|
+
sql = f'"{expr.left.name}" BETWEEN ? AND ?'
|
|
81
|
+
params = tuple(expr.right)
|
|
82
|
+
return sql, params
|
|
83
|
+
elif expr.op in ("IS NULL", "IS NOT NULL"):
|
|
84
|
+
sql = f'"{expr.left.name}" {expr.op}'
|
|
85
|
+
return sql, ()
|
|
86
|
+
elif isinstance(expr.left, _Aggregate):
|
|
87
|
+
sql = f"{expr.left} {expr.op} ?"
|
|
88
|
+
params = (expr.right,)
|
|
89
|
+
return sql, params
|
|
90
|
+
else:
|
|
91
|
+
sql = f'"{expr.left.name}" {expr.op} ?'
|
|
92
|
+
params = (expr.right,)
|
|
93
|
+
return sql, params
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _analysis_code(query):
|
|
97
|
+
from re import match
|
|
98
|
+
if isinstance(query, (list, tuple)):
|
|
99
|
+
for i in query:
|
|
100
|
+
_analysis_code(i)
|
|
101
|
+
return
|
|
102
|
+
if not match("^[A-Za-z_][A-Za-z0-9_.(), ]*$", query) or "sqlite_" in query.lower():
|
|
103
|
+
raise YouHackerError(f"you hacker for {query!r}.") from None
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class Connect:
|
|
107
|
+
__slots__ = ("_con", "_cur", "_changes", "_path")
|
|
108
|
+
def __init__(self, database_path: str) -> None:
|
|
109
|
+
from sqlite3 import connect as _cn
|
|
110
|
+
self._path = database_path
|
|
111
|
+
self._con = _cn(database_path)
|
|
112
|
+
self._cur = self._con.cursor()
|
|
113
|
+
self._changes: list = []
|
|
114
|
+
del _cn
|
|
115
|
+
|
|
116
|
+
# ____________| TABLE |____________
|
|
117
|
+
def add_table(self, table_name: str, *columns: tuple, if_not_exists=False) -> None:
|
|
118
|
+
_analysis_code(table_name)
|
|
119
|
+
query = "CREATE TABLE "
|
|
120
|
+
if if_not_exists:
|
|
121
|
+
query += "IF NOT EXISTS "
|
|
122
|
+
query += f"{table_name} ("
|
|
123
|
+
for column in columns:
|
|
124
|
+
_analysis_code(column)
|
|
125
|
+
name, type = column[0], column[1]
|
|
126
|
+
try:
|
|
127
|
+
limits = column[2]
|
|
128
|
+
query += f"{name} {type} {" ".join(limits)}"
|
|
129
|
+
except:
|
|
130
|
+
query += f"{name} {type}"
|
|
131
|
+
|
|
132
|
+
query += ", "
|
|
133
|
+
query = query[:-2]+")"
|
|
134
|
+
self._changes.append((query,))
|
|
135
|
+
|
|
136
|
+
def rename_table(self, old_name_table: str, new_name_table: str) -> None:
|
|
137
|
+
_analysis_code(old_name_table)
|
|
138
|
+
_analysis_code(new_name_table)
|
|
139
|
+
self._changes.append((f"ALTER TABLE {old_name_table} RENAME TO {new_name_table}",))
|
|
140
|
+
|
|
141
|
+
def drop_table(self, table_name: str) -> None:
|
|
142
|
+
_analysis_code(table_name)
|
|
143
|
+
self._changes.append((f"DROP TABLE {table_name}",))
|
|
144
|
+
|
|
145
|
+
def exist_table(self, table_name: str) -> bool:
|
|
146
|
+
_analysis_code(table_name)
|
|
147
|
+
return table_name in [i[0] for i in self._cur.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()]
|
|
148
|
+
|
|
149
|
+
def copy_table(self, table_name: str, new_name_table: str) -> None:
|
|
150
|
+
_analysis_code(table_name)
|
|
151
|
+
_analysis_code(new_name_table)
|
|
152
|
+
self._changes.append((f"CREATE TABLE {new_name_table} AS SELECT * FROM {table_name}"),)
|
|
153
|
+
|
|
154
|
+
def get_tables(self) -> list:
|
|
155
|
+
return [i[0] for i in self._cur.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()]
|
|
156
|
+
|
|
157
|
+
# ____________| COLUMN |____________
|
|
158
|
+
def add_column(self, table_name: str, column_name: str, column_type: str, limits: list | str=[]) -> None:
|
|
159
|
+
_analysis_code(table_name)
|
|
160
|
+
_analysis_code(column_name)
|
|
161
|
+
_analysis_code(column_type)
|
|
162
|
+
if limits:
|
|
163
|
+
_analysis_code(limits)
|
|
164
|
+
limits = " ".join(limits)
|
|
165
|
+
else:
|
|
166
|
+
limits = ""
|
|
167
|
+
self._changes.append((f"ALTER TABLE {table_name} ADD COLUMN {column_name} {column_type} {limits}",))
|
|
168
|
+
|
|
169
|
+
def drop_column(self, table_name: str, column_name: str) -> None:
|
|
170
|
+
_analysis_code(table_name)
|
|
171
|
+
_analysis_code(column_name)
|
|
172
|
+
self._changes.append((f"ALTER TABLE {table_name} DROP COLUMN {column_name}",))
|
|
173
|
+
|
|
174
|
+
def rename_column(self, table_name: str, old_name_column: str, new_name_column: str) -> None:
|
|
175
|
+
_analysis_code(table_name)
|
|
176
|
+
_analysis_code(old_name_column)
|
|
177
|
+
_analysis_code(new_name_column)
|
|
178
|
+
self._changes.append((f"ALTER TABLE {table_name} RENAME COLUMN {old_name_column} TO {new_name_column}",))
|
|
179
|
+
|
|
180
|
+
def exist_column(self, table_name: str, column_name: str) -> bool:
|
|
181
|
+
_analysis_code(table_name)
|
|
182
|
+
_analysis_code(column_name)
|
|
183
|
+
return column_name in [i[1] for i in self._cur.execute(f"PRAGMA table_info({table_name})").fetchall()]
|
|
184
|
+
|
|
185
|
+
def get_columns(self, table_name: str) -> list:
|
|
186
|
+
_analysis_code(table_name)
|
|
187
|
+
return [i[1] for i in self._cur.execute(f"PRAGMA table_info({table_name})").fetchall()]
|
|
188
|
+
|
|
189
|
+
# ____________| RECORD |____________
|
|
190
|
+
def find_record(self, table_name: str, columns: None | tuple=None, compound: None | tuple=None, condition: None | _Expression=None, bundle: None | tuple=None, filter_bundle: None | tuple=None, sort: None | tuple=None, several: None | int=None, jump: int=0, unique: bool=False):
|
|
191
|
+
_analysis_code(table_name)
|
|
192
|
+
query = "SELECT "
|
|
193
|
+
param = ()
|
|
194
|
+
if unique:
|
|
195
|
+
query += "DISTINCT "
|
|
196
|
+
if columns:
|
|
197
|
+
_analysis_code(columns)
|
|
198
|
+
query += f"{', '.join(columns) if columns else '*'} FROM {table_name}"
|
|
199
|
+
if compound:
|
|
200
|
+
if compound[0].upper() not in ("INNER", "LEFT"):
|
|
201
|
+
raise YouHackerError(f"you hacker for {query!r}.") from None
|
|
202
|
+
_analysis_code(compound)
|
|
203
|
+
query += f" {compound[0]} JOIN \"{compound[1]}\" ON {compound[2]} = {compound[3]}"
|
|
204
|
+
if condition:
|
|
205
|
+
_: tuple = _compile(condition)
|
|
206
|
+
query += f" WHERE {_[0]}"
|
|
207
|
+
param += _[1]
|
|
208
|
+
del _
|
|
209
|
+
if bundle:
|
|
210
|
+
_analysis_code(bundle)
|
|
211
|
+
query += f" GROUP BY {", ".join(bundle)}"
|
|
212
|
+
if filter_bundle:
|
|
213
|
+
__: tuple = _compile(filter_bundle)
|
|
214
|
+
query += f" HAVING {__[0]}"
|
|
215
|
+
param += __[1]
|
|
216
|
+
del __
|
|
217
|
+
|
|
218
|
+
if sort:
|
|
219
|
+
_analysis_code(sort)
|
|
220
|
+
query += " ORDER BY "
|
|
221
|
+
if sort[-1].upper() == "ASC" or sort[-1].upper() == "DESC":
|
|
222
|
+
query += f"{", ".join(sort[:-1])} {sort[-1]}"
|
|
223
|
+
else:
|
|
224
|
+
query += ", ".join(sort)
|
|
225
|
+
if several is not None:
|
|
226
|
+
if not isinstance(several, int):
|
|
227
|
+
raise YouHackerError(f"you hacker for {several!r}.")
|
|
228
|
+
query += f" LIMIT {several}"
|
|
229
|
+
if jump:
|
|
230
|
+
if not isinstance(jump, int):
|
|
231
|
+
raise YouHackerError(f"you hacker for {jump!r}.")
|
|
232
|
+
query += f" OFFSET {jump}"
|
|
233
|
+
return self._cur.execute(query, param).fetchall()
|
|
234
|
+
|
|
235
|
+
def add_record(self, table_name: str, record_info: tuple) -> None:
|
|
236
|
+
_analysis_code(table_name)
|
|
237
|
+
self._changes.append((f"INSERT INTO {table_name} VALUES({', '.join(['?']*len(record_info))})", record_info))
|
|
238
|
+
|
|
239
|
+
def add_records(self, table_name: str, info_records: tuple) -> None:
|
|
240
|
+
_analysis_code(table_name)
|
|
241
|
+
try:
|
|
242
|
+
self._cur.executemany(f"INSERT INTO {table_name} VALUES ({", ".join(["?"]*len(info_records[0]))})", info_records)
|
|
243
|
+
self._con.commit()
|
|
244
|
+
except Exception as e:
|
|
245
|
+
_handler_error(e)
|
|
246
|
+
|
|
247
|
+
def delete_record(self, table_name, condition):
|
|
248
|
+
_analysis_code(table_name)
|
|
249
|
+
query = f"DELETE FROM {table_name}"
|
|
250
|
+
sql_where, params = _compile(condition)
|
|
251
|
+
query += " WHERE " + sql_where
|
|
252
|
+
self._changes.append((query, params))
|
|
253
|
+
|
|
254
|
+
def delete_all_record(self, table_name: str) -> None:
|
|
255
|
+
_analysis_code(table_name)
|
|
256
|
+
self._changes.append((f"DELETE FROM {table_name}",))
|
|
257
|
+
|
|
258
|
+
def edit_record(self, table_name, new_info_record, condition=None):
|
|
259
|
+
_analysis_code(table_name)
|
|
260
|
+
query = f"UPDATE {table_name} SET "
|
|
261
|
+
params = ()
|
|
262
|
+
|
|
263
|
+
set_parts = []
|
|
264
|
+
for key, value in new_info_record.items():
|
|
265
|
+
_analysis_code(key)
|
|
266
|
+
set_parts.append(f'"{key}" = ?')
|
|
267
|
+
params += (value,)
|
|
268
|
+
query += ", ".join(set_parts)
|
|
269
|
+
|
|
270
|
+
if condition:
|
|
271
|
+
sql_where, where_params = _compile(condition)
|
|
272
|
+
query += " WHERE " + sql_where
|
|
273
|
+
params += where_params
|
|
274
|
+
|
|
275
|
+
self._changes.append((query, params))
|
|
276
|
+
|
|
277
|
+
def count_record(self, table_name: str) -> int:
|
|
278
|
+
_analysis_code(table_name)
|
|
279
|
+
return self._cur.execute(f"SELECT COUNT(*) FROM {table_name}").fetchall()[0][0]
|
|
280
|
+
|
|
281
|
+
def upsert_record(self, table_name: str, info_record: tuple, conflict: tuple) -> None:
|
|
282
|
+
_analysis_code(table_name)
|
|
283
|
+
_analysis_code(conflict)
|
|
284
|
+
query = f"INSERT INTO {table_name} VALUES ({", ".join(["?"]*len(info_record))}) ON CONFLICT(\"{'", "'.join(conflict)}\") DO UPDATE SET "
|
|
285
|
+
param = info_record
|
|
286
|
+
colue = dict(zip(self.get_columns(table_name), info_record)) # columns value
|
|
287
|
+
for i in conflict:
|
|
288
|
+
del colue[i]
|
|
289
|
+
for key, value in colue.items():
|
|
290
|
+
query += f'"{key}"=?, '
|
|
291
|
+
param += (value,)
|
|
292
|
+
query = query[:-2]
|
|
293
|
+
self._changes.append((query, param))
|
|
294
|
+
|
|
295
|
+
# ____________| INDEX |_________
|
|
296
|
+
def add_index(self, table_name: str, column_name: str, unique: bool=False) -> None:
|
|
297
|
+
_analysis_code(table_name)
|
|
298
|
+
_analysis_code(column_name)
|
|
299
|
+
self._changes.append((f"CREATE INDEX{" UNIQUE" if unique else ""} {table_name}_{column_name} ON {table_name} ({column_name})",))
|
|
300
|
+
|
|
301
|
+
def delete_index(self, table_name: str, column_name: str) -> None:
|
|
302
|
+
_analysis_code(table_name)
|
|
303
|
+
_analysis_code(column_name)
|
|
304
|
+
self._changes.append((f"DROP INDEX {table_name}_{column_name}",))
|
|
305
|
+
|
|
306
|
+
# ____________| VIEW |_________
|
|
307
|
+
def add_view(self, view_name: str, query: str) -> None:
|
|
308
|
+
raise YouHackerError("add_view is disabled for security reasons.")
|
|
309
|
+
|
|
310
|
+
def delete_view(self, view_name: str) -> None:
|
|
311
|
+
_analysis_code(view_name)
|
|
312
|
+
self._changes.append((f"DROP VIEW {view_name}",))
|
|
313
|
+
|
|
314
|
+
def exist_view(self, view_name: str) -> bool:
|
|
315
|
+
_analysis_code(view_name)
|
|
316
|
+
return view_name in [i[0] for i in self._cur.execute("SELECT name FROM sqlite_master WHERE type='view'").fetchall()]
|
|
317
|
+
|
|
318
|
+
# ____________| BACKUP |_________
|
|
319
|
+
def backup_database(self, backup_path: str | None=None) -> None:
|
|
320
|
+
from shutil import copy2
|
|
321
|
+
from os.path import abspath, dirname, join
|
|
322
|
+
self._con.commit()
|
|
323
|
+
allowed_dir = dirname(abspath(self._path))
|
|
324
|
+
if backup_path:
|
|
325
|
+
if not abspath(backup_path).startswith(allowed_dir):
|
|
326
|
+
raise YouHackerError(f"you hacker for {backup_path!r}.")
|
|
327
|
+
copy2(self._path, backup_path)
|
|
328
|
+
else:
|
|
329
|
+
copy2(self._path, join(allowed_dir, "backup.db"))
|
|
330
|
+
|
|
331
|
+
# ____________| PANDAS |_________
|
|
332
|
+
def to_dataframe(self, table_name: str) -> "pd.DataFrame":
|
|
333
|
+
_analysis_code(table_name)
|
|
334
|
+
import pandas as pd
|
|
335
|
+
columns = self.get_columns(table_name)
|
|
336
|
+
result = self._cur.execute(f"SELECT * FROM {table_name}").fetchall()
|
|
337
|
+
return pd.DataFrame(result, columns=columns)
|
|
338
|
+
|
|
339
|
+
# ____________| CSV |_________
|
|
340
|
+
def load_csv(self, table_name: str, csv_path: str) -> None:
|
|
341
|
+
_analysis_code(table_name)
|
|
342
|
+
from os.path import abspath, dirname
|
|
343
|
+
allowed_dir = dirname(abspath(self._path))
|
|
344
|
+
if not abspath(csv_path).startswith(allowed_dir):
|
|
345
|
+
raise YouHackerError(f"you hacker for {csv_path!r}.")
|
|
346
|
+
import csv as _csv
|
|
347
|
+
|
|
348
|
+
with open(csv_path) as file:
|
|
349
|
+
reader = _csv.reader(file)
|
|
350
|
+
header = next(reader)
|
|
351
|
+
|
|
352
|
+
self.add_table(table_name, (header[0], "TEXT"))
|
|
353
|
+
for column in header[1:]:
|
|
354
|
+
self.add_column(table_name, column, "TEXT")
|
|
355
|
+
|
|
356
|
+
self.save_to_database()
|
|
357
|
+
|
|
358
|
+
records = []
|
|
359
|
+
for row in reader:
|
|
360
|
+
records.append(tuple(row))
|
|
361
|
+
if records:
|
|
362
|
+
self.add_records(table_name, tuple(records))
|
|
363
|
+
|
|
364
|
+
def to_csv(self, table_name: str, csv_path: str) -> None:
|
|
365
|
+
_analysis_code(table_name)
|
|
366
|
+
from os.path import abspath, dirname
|
|
367
|
+
allowed_dir = dirname(abspath(self._path))
|
|
368
|
+
if not abspath(csv_path).startswith(allowed_dir):
|
|
369
|
+
raise YouHackerError(f"you hacker for {csv_path!r}.")
|
|
370
|
+
import csv as _csv
|
|
371
|
+
with open(csv_path, "w", newline="", encoding="utf-8") as f:
|
|
372
|
+
writer = _csv.writer(f)
|
|
373
|
+
writer.writerow(self.get_columns(table_name))
|
|
374
|
+
for row in self.find_record(table_name):
|
|
375
|
+
writer.writerow(row)
|
|
376
|
+
|
|
377
|
+
# ____________| OTHER |_________
|
|
378
|
+
def last_id(self) -> int:
|
|
379
|
+
return self._cur.execute("SELECT last_insert_rowid()").fetchall()[0][0]
|
|
380
|
+
|
|
381
|
+
def database_info(self) -> dict:
|
|
382
|
+
from os.path import basename, exists, getsize
|
|
383
|
+
return {
|
|
384
|
+
"name": basename(self._path),
|
|
385
|
+
"size": getsize(self._path) if exists(self._path) else 0,
|
|
386
|
+
"count_tables": len(self.get_tables())
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
# ____________| BASIC |_________
|
|
391
|
+
def run_query(self, code: str, parameters: tuple=()) -> list:
|
|
392
|
+
raise YouHackerError("run_query is disabled for security reasons.")
|
|
393
|
+
|
|
394
|
+
def optimize(self) -> None:
|
|
395
|
+
self.save_to_database()
|
|
396
|
+
self._cur.execute("VACUUM")
|
|
397
|
+
self._con.commit()
|
|
398
|
+
|
|
399
|
+
def save_to_database(self) -> None:
|
|
400
|
+
try:
|
|
401
|
+
with self._con:
|
|
402
|
+
for sql_code in self._changes:
|
|
403
|
+
self._cur.execute(*sql_code)
|
|
404
|
+
except Exception as e:
|
|
405
|
+
_handler_error(e)
|
|
406
|
+
|
|
407
|
+
finally:
|
|
408
|
+
self._changes.clear()
|
|
409
|
+
|
|
410
|
+
def close(self):
|
|
411
|
+
self._con.close()
|
|
412
|
+
|
|
413
|
+
# ____________| MAGICALS |_________
|
|
414
|
+
def __enter__(self) -> "Connect":
|
|
415
|
+
return self
|
|
416
|
+
|
|
417
|
+
def __exit__(self, exc_type, exc_value, exc_tb) -> None:
|
|
418
|
+
self.save_to_database()
|
|
419
|
+
self.close()
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
# ____________| ERRORS |_________
|
|
423
|
+
class SqlthonError(Exception):pass
|
|
424
|
+
class YouHackerError(SqlthonError, PermissionError):pass
|
|
425
|
+
class TableError(SqlthonError):pass
|
|
426
|
+
class TableNotFoundError(TableError):pass
|
|
427
|
+
class TableAlreadyExistsError(TableError):pass
|
|
428
|
+
class ColumnError(SqlthonError):pass
|
|
429
|
+
class ColumnNotFoundError(ColumnError):pass
|
|
430
|
+
class RecordError(SqlthonError):pass
|
|
431
|
+
class UniqueConstraintError(RecordError):pass
|
|
432
|
+
class NotNullConstraintError(RecordError):pass
|
|
433
|
+
class DataTypeError(RecordError):pass
|
|
434
|
+
class ForeignKeyError(RecordError):pass
|
|
435
|
+
class CheckConstraintError(RecordError):pass
|
|
436
|
+
class PrimaryKeyError(RecordError):pass
|
|
437
|
+
class QueryError(SqlthonError):pass
|
|
438
|
+
class SyntaxError(QueryError):pass
|
|
439
|
+
class NoSuchFunctionError(QueryError):pass
|
|
440
|
+
class WrongNumberOfArgumentsError(QueryError):pass
|
|
441
|
+
class DatabaseError(SqlthonError):pass
|
|
442
|
+
class DatabaseLockedError(DatabaseError):pass
|
|
443
|
+
class DatabaseReadOnlyError(DatabaseError):pass
|
|
444
|
+
class DatabaseCorruptError(DatabaseError):pass
|
|
445
|
+
class DatabaseFullError(DatabaseError):pass
|
|
446
|
+
class DatabaseBusyError(DatabaseError):pass
|
|
447
|
+
class IndexError(SqlthonError):pass
|
|
448
|
+
class IndexNotFoundError(IndexError):pass
|
|
449
|
+
class IndexAlreadyExistsError(IndexError):pass
|
|
450
|
+
class ViewError(SqlthonError):pass
|
|
451
|
+
class ViewNotFoundError(ViewError):pass
|
|
452
|
+
class ViewAlreadyExistsError(ViewError):pass
|
|
453
|
+
class TransactionError(SqlthonError):pass
|
|
454
|
+
class TransactionAlreadyActiveError(TransactionError):pass
|
|
455
|
+
class TransactionNotActiveError(TransactionError):pass
|
|
456
|
+
class BackupError(SqlthonError):pass
|
|
457
|
+
class BackupPathError(BackupError):pass
|
|
458
|
+
class BackupPermissionError(BackupError):pass
|
|
459
|
+
class CsvError(SqlthonError):pass
|
|
460
|
+
class CsvFileNotFoundError(CsvError):pass
|
|
461
|
+
class CsvFormatError(CsvError):pass
|
|
462
|
+
class PandasError(SqlthonError):pass
|
|
463
|
+
class PandasNotInstalledError(PandasError):pass
|
|
464
|
+
class ValidationError(SqlthonError):pass
|
|
465
|
+
class InvalidColumnCountError(ValidationError):pass
|
|
466
|
+
class InvalidValueError(ValidationError):pass
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def _handler_error(e: Exception):
|
|
470
|
+
msg = str(e).lower()
|
|
471
|
+
|
|
472
|
+
if "no such table" in msg:
|
|
473
|
+
raise TableNotFoundError(f"no table with name {msg.split()[-1]!r}.") from None
|
|
474
|
+
|
|
475
|
+
elif "already exists" in msg:
|
|
476
|
+
raise TableAlreadyExistsError(f"table {msg.split()[1]!r} alredy existed.") from None
|
|
477
|
+
|
|
478
|
+
elif "no such column" in msg:
|
|
479
|
+
raise ColumnNotFoundError(f"no column with name {msg.split()[-1]!r}.") from None
|
|
480
|
+
|
|
481
|
+
elif "unique constraint" in msg:
|
|
482
|
+
raise UniqueConstraintError(f"this field {msg.split()[-1]!r} already existed.") from None
|
|
483
|
+
|
|
484
|
+
elif "not null constraint" in msg:
|
|
485
|
+
raise NotNullConstraintError(f"this field cannot be left empty and you sent it {msg.split()[-1]!r}.") from None
|
|
486
|
+
|
|
487
|
+
elif "datatype mismatch" in msg:
|
|
488
|
+
raise DataTypeError(msg) from None
|
|
489
|
+
|
|
490
|
+
elif "foreign key constraint" in msg:
|
|
491
|
+
raise ForeignKeyError(msg) from None
|
|
492
|
+
|
|
493
|
+
elif "check constraint" in msg:
|
|
494
|
+
raise CheckConstraintError(f"check constraint failed {msg.split(": ")[-1]!r}.") from None
|
|
495
|
+
|
|
496
|
+
elif "primary key" in msg:
|
|
497
|
+
raise PrimaryKeyError(msg) from None
|
|
498
|
+
|
|
499
|
+
elif "no such function" in msg:
|
|
500
|
+
raise NoSuchFunctionError(f"no function with name {msg.split()[-1]!r}.") from None
|
|
501
|
+
|
|
502
|
+
elif "wrong number of arguments" in msg:
|
|
503
|
+
raise WrongNumberOfArgumentsError(msg) from None
|
|
504
|
+
|
|
505
|
+
elif "syntax error" in msg:
|
|
506
|
+
raise SyntaxError(f"invalid {msg.split()[-1].replace('"', "'")}") from None
|
|
507
|
+
|
|
508
|
+
elif "database is locked" in msg:
|
|
509
|
+
raise DatabaseLockedError(msg) from None
|
|
510
|
+
|
|
511
|
+
elif "readonly database" in msg:
|
|
512
|
+
raise DatabaseReadOnlyError(msg) from None
|
|
513
|
+
|
|
514
|
+
elif "malformed" in msg:
|
|
515
|
+
raise DatabaseCorruptError(msg) from None
|
|
516
|
+
|
|
517
|
+
elif "disk is full" in msg:
|
|
518
|
+
raise DatabaseFullError(msg) from None
|
|
519
|
+
|
|
520
|
+
elif "database is busy" in msg:
|
|
521
|
+
raise DatabaseBusyError(msg) from None
|
|
522
|
+
|
|
523
|
+
elif "no such index" in msg:
|
|
524
|
+
raise IndexNotFoundError(f"no index with name {msg.split()[-1]!r}.") from None
|
|
525
|
+
|
|
526
|
+
elif "index already exists" in msg:
|
|
527
|
+
raise IndexAlreadyExistsError(f"index {msg.split()[1]!r} already existed.") from None
|
|
528
|
+
|
|
529
|
+
elif "no such view" in msg:
|
|
530
|
+
raise ViewNotFoundError(f"no view with name {msg.split()[-1]!r}.") from None
|
|
531
|
+
|
|
532
|
+
elif "view already exists" in msg:
|
|
533
|
+
raise ViewAlreadyExistsError(f"view {msg.split()[1]!r} already existed.") from None
|
|
534
|
+
|
|
535
|
+
elif "transaction within a transaction" in msg:
|
|
536
|
+
raise TransactionAlreadyActiveError(msg) from None
|
|
537
|
+
|
|
538
|
+
elif "no transaction is active" in msg:
|
|
539
|
+
raise TransactionNotActiveError(msg) from None
|
|
540
|
+
|
|
541
|
+
else:
|
|
542
|
+
raise SqlthonError(msg) from None
|
|
@@ -1,334 +0,0 @@
|
|
|
1
|
-
class Field:
|
|
2
|
-
__slots__ = ("name",)
|
|
3
|
-
def __init__(self, name):
|
|
4
|
-
self.name = name
|
|
5
|
-
|
|
6
|
-
def __gt__(self, value): return _Expression(self, ">", value)
|
|
7
|
-
def __lt__(self, value): return _Expression(self, "<", value)
|
|
8
|
-
def __ge__(self, value): return _Expression(self, ">=", value)
|
|
9
|
-
def __le__(self, value): return _Expression(self, "<=", value)
|
|
10
|
-
def __eq__(self, value): return _Expression(self, "=", value)
|
|
11
|
-
def __ne__(self, value): return _Expression(self, "!=", value)
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
class _Expression:
|
|
15
|
-
__slots__ = ("left", "op", "right")
|
|
16
|
-
def __init__(self, left, op, right):
|
|
17
|
-
self.left = left
|
|
18
|
-
self.op = op
|
|
19
|
-
self.right = right
|
|
20
|
-
|
|
21
|
-
def __and__(self, other):
|
|
22
|
-
return _Expression(self, "AND", other)
|
|
23
|
-
def __or__(self, other):
|
|
24
|
-
return _Expression(self, "OR", other)
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
class _Aggregate:
|
|
28
|
-
__slots__ = ("func", "column")
|
|
29
|
-
def __init__(self, func, column="*"):
|
|
30
|
-
self.func = func
|
|
31
|
-
self.column = column
|
|
32
|
-
|
|
33
|
-
def __gt__(self, value): return _Expression(self, ">", value)
|
|
34
|
-
def __lt__(self, value): return _Expression(self, "<", value)
|
|
35
|
-
def __ge__(self, value): return _Expression(self, ">=", value)
|
|
36
|
-
def __le__(self, value): return _Expression(self, "<=", value)
|
|
37
|
-
def __eq__(self, value): return _Expression(self, "=", value)
|
|
38
|
-
def __ne__(self, value): return _Expression(self, "!=", value)
|
|
39
|
-
|
|
40
|
-
def __str__(self):
|
|
41
|
-
return f"{self.func}({self.column})"
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
def _compile(expr):
|
|
45
|
-
if isinstance(expr.left, _Expression) or isinstance(expr.right, _Expression):
|
|
46
|
-
left_sql, left_params = _compile(expr.left)
|
|
47
|
-
right_sql, right_params = _compile(expr.right)
|
|
48
|
-
sql = f"({left_sql}) {expr.op} ({right_sql})"
|
|
49
|
-
params = left_params + right_params
|
|
50
|
-
return sql, params
|
|
51
|
-
elif isinstance(expr.left, _Aggregate):
|
|
52
|
-
sql = f"{expr.left} {expr.op} ?"
|
|
53
|
-
params = (expr.right,)
|
|
54
|
-
return sql, params
|
|
55
|
-
else:
|
|
56
|
-
sql = f'"{expr.left.name}" {expr.op} ?'
|
|
57
|
-
params = (expr.right,)
|
|
58
|
-
return sql, params
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
class Connect:
|
|
62
|
-
__slots__ = ("_con", "_cur", "_changes", "_path", "_turbo")
|
|
63
|
-
def __init__(self, database_path: str) -> None:
|
|
64
|
-
from sqlite3 import connect as _cn
|
|
65
|
-
self._path = database_path
|
|
66
|
-
self._con = _cn(database_path)
|
|
67
|
-
self._cur = self._con.cursor()
|
|
68
|
-
self._changes: list = []
|
|
69
|
-
self._turbo: bool = False
|
|
70
|
-
del _cn
|
|
71
|
-
|
|
72
|
-
# ____________| TABLE |____________
|
|
73
|
-
def add_table(self, table_name: str, *columns: tuple, if_not_exists=False) -> None:
|
|
74
|
-
query = "CREATE TABLE "
|
|
75
|
-
if if_not_exists:
|
|
76
|
-
query += "IF NOT EXISTS "
|
|
77
|
-
query += f"{table_name} ("
|
|
78
|
-
for column in columns:
|
|
79
|
-
name, type = column[0], column[1]
|
|
80
|
-
try:
|
|
81
|
-
limits = column[2]
|
|
82
|
-
query += f"{name} {type} {" ".join(limits)}"
|
|
83
|
-
except:
|
|
84
|
-
query += f"{name} {type}"
|
|
85
|
-
|
|
86
|
-
query += ", "
|
|
87
|
-
query = query[:-2]+")"
|
|
88
|
-
self._changes.append((query,))
|
|
89
|
-
|
|
90
|
-
def rename_table(self, old_name_table: str, new_name_table: str) -> None:
|
|
91
|
-
self._changes.append((f"ALTER TABLE {old_name_table} RENAME TO {new_name_table}",))
|
|
92
|
-
|
|
93
|
-
def drop_table(self, table_name: str) -> None:
|
|
94
|
-
self._changes.append((f"DROP TABLE {table_name}",))
|
|
95
|
-
|
|
96
|
-
def exist_table(self, table_name: str) -> bool:
|
|
97
|
-
return table_name in [i[0] for i in self.run_query("SELECT name FROM sqlite_master WHERE type='table'")]
|
|
98
|
-
|
|
99
|
-
def copy_table(self, table_name: str, new_name_table: str) -> None:
|
|
100
|
-
self._changes.append((f"CREATE TABLE {new_name_table} AS SELECT * FROM {table_name}"),)
|
|
101
|
-
|
|
102
|
-
def get_tables(self) -> list:
|
|
103
|
-
return [i[0] for i in self.run_query("SELECT name FROM sqlite_master WHERE type='table'")]
|
|
104
|
-
|
|
105
|
-
# ____________| COLUMN |____________
|
|
106
|
-
def add_column(self, table_name: str, column_name: str, column_type: str, limits: list | str=[]) -> None:
|
|
107
|
-
if limits:
|
|
108
|
-
limits = " ".join(limits)
|
|
109
|
-
else:
|
|
110
|
-
limits = ""
|
|
111
|
-
self._changes.append((f"ALTER TABLE {table_name} ADD COLUMN {column_name} {column_type} {limits}",))
|
|
112
|
-
|
|
113
|
-
def drop_column(self, table_name: str, column_name: str) -> None:
|
|
114
|
-
self._changes.append((f"ALTER TABLE {table_name} DROP COLUMN {column_name}",))
|
|
115
|
-
|
|
116
|
-
def rename_column(self, table_name: str, old_name_column: str, new_name_column: str) -> None:
|
|
117
|
-
self._changes.append((f"ALTER TABLE {table_name} RENAME COLUMN {old_name_column} TO {new_name_column}",))
|
|
118
|
-
|
|
119
|
-
def exist_column(self, table_name: str, column_name: str) -> bool:
|
|
120
|
-
return column_name in [i[1] for i in self.run_query(f"PRAGMA table_info({table_name})")]
|
|
121
|
-
|
|
122
|
-
def get_columns(self, table_name: str) -> list:
|
|
123
|
-
return [i[1] for i in self.run_query(f"PRAGMA table_info({table_name})")]
|
|
124
|
-
|
|
125
|
-
# ____________| RECORD |____________
|
|
126
|
-
def find_record(self, table_name: str, columns: None | tuple=None, compound: None | tuple=None, condition: None | _Expression=None, bundle: None | tuple=None, filter_bundle: None | tuple=None, sort: None | tuple=None, several: None | int=None, jump: int=0, unique: bool=False):
|
|
127
|
-
query = "SELECT "
|
|
128
|
-
param = ()
|
|
129
|
-
if unique:
|
|
130
|
-
query += "DISTINCT "
|
|
131
|
-
query += f"{', '.join(columns) if columns else '*'} FROM {table_name}"
|
|
132
|
-
if compound:
|
|
133
|
-
query += f" {compound[0]} JOIN \"{compound[1]}\" ON {compound[2]} = {compound[3]}"
|
|
134
|
-
if condition:
|
|
135
|
-
_: tuple = _compile(condition)
|
|
136
|
-
query += f" WHERE {_[0]}"
|
|
137
|
-
param += _[1]
|
|
138
|
-
del _
|
|
139
|
-
if bundle:
|
|
140
|
-
query += f" GROUP BY {", ".join(bundle)}"
|
|
141
|
-
if filter_bundle:
|
|
142
|
-
__: tuple = _compile(filter_bundle)
|
|
143
|
-
query += f" HAVING {__[0]}"
|
|
144
|
-
param += __[1]
|
|
145
|
-
del __
|
|
146
|
-
|
|
147
|
-
if sort:
|
|
148
|
-
query += " ORDER BY "
|
|
149
|
-
if sort[-1].upper() == "ASC" or sort[-1].upper() == "DESC":
|
|
150
|
-
query += f"{", ".join(sort[:-1])} {sort[-1]}"
|
|
151
|
-
else:
|
|
152
|
-
query += ", ".join(sort)
|
|
153
|
-
if several is not None:
|
|
154
|
-
query += f" LIMIT {several}"
|
|
155
|
-
if jump:
|
|
156
|
-
query += f" OFFSET {jump}"
|
|
157
|
-
return self.run_query(query, param)
|
|
158
|
-
|
|
159
|
-
def add_record(self, table_name: str, record_info: tuple) -> None:
|
|
160
|
-
self._changes.append((f"INSERT INTO {table_name} VALUES({', '.join(['?']*len(record_info))})", record_info))
|
|
161
|
-
|
|
162
|
-
def add_records(self, table_name: str, info_records: tuple) -> None:
|
|
163
|
-
self._cur.executemany(f"INSERT INTO {table_name} VALUES ({", ".join(["?"]*len(info_records[0]))})", info_records)
|
|
164
|
-
self._con.commit()
|
|
165
|
-
|
|
166
|
-
def delete_record(self, table_name, condition):
|
|
167
|
-
query = f"DELETE FROM {table_name}"
|
|
168
|
-
sql_where, params = _compile(condition)
|
|
169
|
-
query += " WHERE " + sql_where
|
|
170
|
-
self._changes.append((query, params))
|
|
171
|
-
|
|
172
|
-
def delete_all_record(self, table_name: str) -> None:
|
|
173
|
-
self._changes.append((f"DELETE FROM {table_name}",))
|
|
174
|
-
|
|
175
|
-
def edit_record(self, table_name, new_info_record, condition=None):
|
|
176
|
-
query = f"UPDATE {table_name} SET "
|
|
177
|
-
params = ()
|
|
178
|
-
|
|
179
|
-
set_parts = []
|
|
180
|
-
for key, value in new_info_record.items():
|
|
181
|
-
set_parts.append(f'"{key}" = ?')
|
|
182
|
-
params += (value,)
|
|
183
|
-
query += ", ".join(set_parts)
|
|
184
|
-
|
|
185
|
-
if condition:
|
|
186
|
-
sql_where, where_params = _compile(condition)
|
|
187
|
-
query += " WHERE " + sql_where
|
|
188
|
-
params += where_params
|
|
189
|
-
|
|
190
|
-
self._changes.append((query, params))
|
|
191
|
-
|
|
192
|
-
def count_record(self, table_name: str) -> int:
|
|
193
|
-
return self.run_query(f"SELECT COUNT(*) FROM {table_name}")[0][0]
|
|
194
|
-
|
|
195
|
-
def upsert_record(self, table_name: str, info_record: tuple, conflict: tuple) -> None:
|
|
196
|
-
query = f"INSERT INTO {table_name} VALUES ({", ".join(["?"]*len(info_record))}) ON CONFLICT(\"{'", "'.join(conflict)}\") DO UPDATE SET "
|
|
197
|
-
param = info_record
|
|
198
|
-
colue = dict(zip(self.get_columns(table_name), info_record)) # columns value
|
|
199
|
-
for i in conflict:
|
|
200
|
-
del colue[i]
|
|
201
|
-
for key, value in colue.items():
|
|
202
|
-
query += f'"{key}"=?, '
|
|
203
|
-
param += (value,)
|
|
204
|
-
query = query[:-2]
|
|
205
|
-
self._changes.append((query, param))
|
|
206
|
-
|
|
207
|
-
# ____________| INDEX |_________
|
|
208
|
-
def add_index(self, table_name: str, column_name: str, unique: bool=False) -> None:
|
|
209
|
-
self._changes.append((f"CREATE INDEX{" UNIQUE" if unique else ""} {table_name}_{column_name} ON {table_name} ({column_name})",))
|
|
210
|
-
|
|
211
|
-
def delete_index(self, table_name: str, column_name: str) -> None:
|
|
212
|
-
self._changes.append((f"DROP INDEX {table_name}_{column_name}",))
|
|
213
|
-
|
|
214
|
-
# ____________| VIEW |_________
|
|
215
|
-
def add_view(self, view_name: str, query: str) -> None:
|
|
216
|
-
self._changes.append((f"CREATE VIEW {view_name} AS {query}",))
|
|
217
|
-
|
|
218
|
-
def delete_view(self, view_name: str) -> None:
|
|
219
|
-
self._changes.append((f"DROP VIEW {view_name}",))
|
|
220
|
-
|
|
221
|
-
def exist_view(self, view_name: str) -> bool:
|
|
222
|
-
return view_name in [i[0] for i in self.run_query("SELECT name FROM sqlite_master WHERE type='view'")]
|
|
223
|
-
|
|
224
|
-
# ____________| BACKUP |_________
|
|
225
|
-
def backup_database(self, backup_path: str | None=None) -> None:
|
|
226
|
-
from shutil import copy2
|
|
227
|
-
self._con.commit()
|
|
228
|
-
if backup_path:
|
|
229
|
-
copy2(self._path, backup_path)
|
|
230
|
-
else:
|
|
231
|
-
copy2(self._path, "".join(self._path.split(".")[:-1]))
|
|
232
|
-
|
|
233
|
-
# ____________| PANDAS |_________
|
|
234
|
-
def to_dataframe(self, table_name: str) -> "pd.DataFrame":
|
|
235
|
-
import pandas as pd
|
|
236
|
-
columns = self.get_columns(table_name)
|
|
237
|
-
result = self.run_query(f"SELECT * FROM {table_name}")
|
|
238
|
-
return pd.DataFrame(result, columns=columns)
|
|
239
|
-
|
|
240
|
-
# ____________| CSV |_________
|
|
241
|
-
def load_csv(self, table_name: str, csv_path: str) -> None:
|
|
242
|
-
import csv as _csv
|
|
243
|
-
|
|
244
|
-
with open(csv_path) as file:
|
|
245
|
-
reader = _csv.reader(file)
|
|
246
|
-
header = next(reader)
|
|
247
|
-
|
|
248
|
-
self.add_table(table_name, (header[0], "TEXT"))
|
|
249
|
-
for column in header[1:]:
|
|
250
|
-
self.add_column(table_name, column, "TEXT")
|
|
251
|
-
|
|
252
|
-
self.save_to_database()
|
|
253
|
-
|
|
254
|
-
records = []
|
|
255
|
-
for row in reader:
|
|
256
|
-
records.append(tuple(row))
|
|
257
|
-
if records:
|
|
258
|
-
self.add_records(table_name, tuple(records))
|
|
259
|
-
|
|
260
|
-
def to_csv(self, table_name: str, csv_path: str) -> None:
|
|
261
|
-
import csv as _csv
|
|
262
|
-
with open(csv_path, "w", newline="", encoding="utf-8") as f:
|
|
263
|
-
writer = _csv.writer(f)
|
|
264
|
-
writer.writerow(self.get_columns(table_name))
|
|
265
|
-
for row in self.find_record(table_name):
|
|
266
|
-
writer.writerow(row)
|
|
267
|
-
|
|
268
|
-
# ____________| TURBO |_________
|
|
269
|
-
def on_turbo(self) -> None:
|
|
270
|
-
if self._turbo:
|
|
271
|
-
return
|
|
272
|
-
|
|
273
|
-
self._cur.execute("PRAGMA journal_mode = WAL")
|
|
274
|
-
self._cur.execute("PRAGMA synchronous = OFF")
|
|
275
|
-
self._cur.execute("PRAGMA cache_size = -64000")
|
|
276
|
-
self._cur.execute("PRAGMA temp_store = MEMORY")
|
|
277
|
-
self._turbo = True
|
|
278
|
-
|
|
279
|
-
def off_turbo(self) -> None:
|
|
280
|
-
if not self._turbo:
|
|
281
|
-
return
|
|
282
|
-
|
|
283
|
-
self._cur.execute("PRAGMA synchronous = FULL")
|
|
284
|
-
self._cur.execute("PRAGMA journal_mode = DELETE")
|
|
285
|
-
self._cur.execute("PRAGMA cache_size = -2000")
|
|
286
|
-
self._cur.execute("PRAGMA temp_store = DEFAULT")
|
|
287
|
-
self._turbo = False
|
|
288
|
-
|
|
289
|
-
@property
|
|
290
|
-
def is_turbo(self) -> bool:
|
|
291
|
-
return self._turbo
|
|
292
|
-
|
|
293
|
-
# ____________| OTHER |_________
|
|
294
|
-
def last_id(self) -> int:
|
|
295
|
-
return self.run_query("SELECT last_insert_rowid()")[0][0]
|
|
296
|
-
|
|
297
|
-
def database_info(self) -> dict:
|
|
298
|
-
from os.path import basename, exists, getsize
|
|
299
|
-
return {
|
|
300
|
-
"name": basename(self._path),
|
|
301
|
-
"size": getsize(self._path) if exists(self._path) else 0,
|
|
302
|
-
"count_tables": len(self.get_tables())
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
# ____________| BASIC |_________
|
|
306
|
-
def run_query(self, code: str, parameters: tuple=()) -> list:
|
|
307
|
-
self._cur.execute(code, parameters)
|
|
308
|
-
if not "SELECT" in code:
|
|
309
|
-
self._con.commit()
|
|
310
|
-
return self._cur.fetchall()
|
|
311
|
-
|
|
312
|
-
def optimize(self) -> None:
|
|
313
|
-
self.save_to_database()
|
|
314
|
-
self._cur.execute("VACUUM")
|
|
315
|
-
self._con.commit()
|
|
316
|
-
|
|
317
|
-
def save_to_database(self) -> None:
|
|
318
|
-
try:
|
|
319
|
-
with self._con:
|
|
320
|
-
for sql_code in self._changes:
|
|
321
|
-
self._cur.execute(*sql_code)
|
|
322
|
-
finally:
|
|
323
|
-
self._changes.clear()
|
|
324
|
-
|
|
325
|
-
def close(self):
|
|
326
|
-
self._con.close()
|
|
327
|
-
|
|
328
|
-
# ____________| MAGICALS |_________
|
|
329
|
-
def __enter__(self) -> "Connect":
|
|
330
|
-
return self
|
|
331
|
-
|
|
332
|
-
def __exit__(self, exc_type, exc_value, exc_tb) -> None:
|
|
333
|
-
self.save_to_database()
|
|
334
|
-
self.close()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|