sqlengine-lite 2.2.2__tar.gz → 2.2.4__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.
- {sqlengine_lite-2.2.2/src/sqlengine_lite.egg-info → sqlengine_lite-2.2.4}/PKG-INFO +13 -2
- {sqlengine_lite-2.2.2 → sqlengine_lite-2.2.4}/README.md +12 -1
- {sqlengine_lite-2.2.2 → sqlengine_lite-2.2.4}/pyproject.toml +1 -1
- sqlengine_lite-2.2.4/src/sqlengine/_internal/adapters.py +13 -0
- {sqlengine_lite-2.2.2 → sqlengine_lite-2.2.4}/src/sqlengine/_internal/connection_manager.py +92 -16
- sqlengine_lite-2.2.4/src/sqlengine/_internal/metaclasses.py +87 -0
- {sqlengine_lite-2.2.2 → sqlengine_lite-2.2.4}/src/sqlengine/_internal/sqlgen.py +36 -1
- {sqlengine_lite-2.2.2 → sqlengine_lite-2.2.4}/src/sqlengine/_internal/statements.py +81 -12
- {sqlengine_lite-2.2.2 → sqlengine_lite-2.2.4}/src/sqlengine/_internal/types.py +43 -15
- {sqlengine_lite-2.2.2 → sqlengine_lite-2.2.4}/src/sqlengine/exceptions.py +11 -1
- {sqlengine_lite-2.2.2 → sqlengine_lite-2.2.4}/src/sqlengine/schema.py +3 -3
- {sqlengine_lite-2.2.2 → sqlengine_lite-2.2.4}/src/sqlengine/sqltable.py +58 -107
- {sqlengine_lite-2.2.2 → sqlengine_lite-2.2.4}/src/sqlengine/utils/connection.py +2 -1
- {sqlengine_lite-2.2.2 → sqlengine_lite-2.2.4/src/sqlengine_lite.egg-info}/PKG-INFO +13 -2
- {sqlengine_lite-2.2.2 → sqlengine_lite-2.2.4}/src/sqlengine_lite.egg-info/SOURCES.txt +2 -0
- {sqlengine_lite-2.2.2 → sqlengine_lite-2.2.4}/tests/test.py +100 -22
- {sqlengine_lite-2.2.2 → sqlengine_lite-2.2.4}/LICENSE +0 -0
- {sqlengine_lite-2.2.2 → sqlengine_lite-2.2.4}/setup.cfg +0 -0
- {sqlengine_lite-2.2.2 → sqlengine_lite-2.2.4}/src/sqlengine/__init__.py +0 -0
- {sqlengine_lite-2.2.2 → sqlengine_lite-2.2.4}/src/sqlengine/_internal/__init__.py +0 -0
- {sqlengine_lite-2.2.2 → sqlengine_lite-2.2.4}/src/sqlengine/_internal/repr.py +0 -0
- {sqlengine_lite-2.2.2 → sqlengine_lite-2.2.4}/src/sqlengine/utils/__init__.py +0 -0
- {sqlengine_lite-2.2.2 → sqlengine_lite-2.2.4}/src/sqlengine/utils/convert.py +0 -0
- {sqlengine_lite-2.2.2 → sqlengine_lite-2.2.4}/src/sqlengine_lite.egg-info/dependency_links.txt +0 -0
- {sqlengine_lite-2.2.2 → sqlengine_lite-2.2.4}/src/sqlengine_lite.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: sqlengine-lite
|
|
3
|
-
Version: 2.2.
|
|
3
|
+
Version: 2.2.4
|
|
4
4
|
Summary: Cute sqlite3 wrapper for sql tables
|
|
5
5
|
Project-URL: Homepage, https://github.com/suffermuffin/SQL-Engine
|
|
6
6
|
Project-URL: Repository, https://github.com/suffermuffin/SQL-Engine.git
|
|
@@ -69,7 +69,18 @@ table.select("InvoiceId", "CustomerId", "BillingAddress", "BillingCountry", "Tot
|
|
|
69
69
|
|
|
70
70
|
## Purpose
|
|
71
71
|
|
|
72
|
-
It's a tiny little modern ORM-like that lets you prototype your databases locally with great flexibility. Also, it can be used in production apps to store and retrieve data, because all select, update, delete queries are parametrized. But it does not restrict you from using your own queries which might not be parameterized with methods like `select.
|
|
72
|
+
It's a tiny little modern ORM-like that lets you prototype your databases locally with great flexibility. Also, it can be used in production apps to store and retrieve data, because all **values** in select, update, delete and insert queries are parametrized. But it does not restrict you from using your own queries which might not be parameterized with methods like `select.custom_query()` and `where.custom()`. Flexibility is a go to for this library.
|
|
73
|
+
|
|
74
|
+
> [!WARNING]
|
|
75
|
+
> **Column names are raw SQL.** Values are always passed as parameters, but column names and expressions given as strings are inserted into the query exactly as written. That is what lets you write `select("COUNT(x)")` or `order_by("Salary * 2")`, but it also means that such strings must never come from user input, or it opens the way to SQL injection:
|
|
76
|
+
>
|
|
77
|
+
> ```py
|
|
78
|
+
> table.select("Name").where.eq("ID", user_input) # safe, value is a parameter
|
|
79
|
+
> table.select("Name").where.eq(user_input, 5) # unsafe, column name is raw SQL
|
|
80
|
+
> table.select("Name").order_by(request.args["sort"]) # unsafe
|
|
81
|
+
> ```
|
|
82
|
+
>
|
|
83
|
+
> If a column name has to depend on user input, check it against `table.columns` first.
|
|
73
84
|
|
|
74
85
|
And last (but not least) is data inspection. If you need to quickly inspect existing .db file but don't want to install yet another heavy ORM with a lot of unused dependencies and features, you might look into SqlEngine, as it uses only native python modules, implements dynamic schema builder and has a good synergy with Jupyter Notebook.
|
|
75
86
|
|
|
@@ -57,7 +57,18 @@ table.select("InvoiceId", "CustomerId", "BillingAddress", "BillingCountry", "Tot
|
|
|
57
57
|
|
|
58
58
|
## Purpose
|
|
59
59
|
|
|
60
|
-
It's a tiny little modern ORM-like that lets you prototype your databases locally with great flexibility. Also, it can be used in production apps to store and retrieve data, because all select, update, delete queries are parametrized. But it does not restrict you from using your own queries which might not be parameterized with methods like `select.
|
|
60
|
+
It's a tiny little modern ORM-like that lets you prototype your databases locally with great flexibility. Also, it can be used in production apps to store and retrieve data, because all **values** in select, update, delete and insert queries are parametrized. But it does not restrict you from using your own queries which might not be parameterized with methods like `select.custom_query()` and `where.custom()`. Flexibility is a go to for this library.
|
|
61
|
+
|
|
62
|
+
> [!WARNING]
|
|
63
|
+
> **Column names are raw SQL.** Values are always passed as parameters, but column names and expressions given as strings are inserted into the query exactly as written. That is what lets you write `select("COUNT(x)")` or `order_by("Salary * 2")`, but it also means that such strings must never come from user input, or it opens the way to SQL injection:
|
|
64
|
+
>
|
|
65
|
+
> ```py
|
|
66
|
+
> table.select("Name").where.eq("ID", user_input) # safe, value is a parameter
|
|
67
|
+
> table.select("Name").where.eq(user_input, 5) # unsafe, column name is raw SQL
|
|
68
|
+
> table.select("Name").order_by(request.args["sort"]) # unsafe
|
|
69
|
+
> ```
|
|
70
|
+
>
|
|
71
|
+
> If a column name has to depend on user input, check it against `table.columns` first.
|
|
61
72
|
|
|
62
73
|
And last (but not least) is data inspection. If you need to quickly inspect existing .db file but don't want to install yet another heavy ORM with a lot of unused dependencies and features, you might look into SqlEngine, as it uses only native python modules, implements dynamic schema builder and has a good synergy with Jupyter Notebook.
|
|
63
74
|
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
""" Default adapters """
|
|
2
|
+
from sqlite3 import register_converter
|
|
3
|
+
|
|
4
|
+
BOOL_SQL = "BOOLEAN"
|
|
5
|
+
|
|
6
|
+
def register_boolean():
|
|
7
|
+
register_converter(BOOL_SQL, lambda x: bool(int(x)))
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
REGISTRY_MAP = {
|
|
11
|
+
bool : register_boolean,
|
|
12
|
+
bool | None : register_boolean
|
|
13
|
+
}
|
|
@@ -2,11 +2,17 @@ import sqlite3
|
|
|
2
2
|
import logging
|
|
3
3
|
import os
|
|
4
4
|
|
|
5
|
-
from typing import overload, Literal, Sequence
|
|
5
|
+
from typing import overload, Literal, Sequence, Any
|
|
6
6
|
from contextlib import contextmanager
|
|
7
|
+
from pathlib import Path
|
|
7
8
|
|
|
8
|
-
from .types import SqlValue, SqlRow
|
|
9
|
-
from ..exceptions import
|
|
9
|
+
from .types import SqlValue, SqlRow, FetchRow
|
|
10
|
+
from ..exceptions import (
|
|
11
|
+
TransactionError,
|
|
12
|
+
NestedTransactionError,
|
|
13
|
+
OutsideTransactionError,
|
|
14
|
+
TableIndexError
|
|
15
|
+
)
|
|
10
16
|
|
|
11
17
|
|
|
12
18
|
logger = logging.getLogger("sqlengine")
|
|
@@ -27,7 +33,7 @@ class ConnectionManager:
|
|
|
27
33
|
_trans : sqlite3.Connection
|
|
28
34
|
_trans_cursor : sqlite3.Cursor
|
|
29
35
|
|
|
30
|
-
def __init__(self, database : str, **connection_params) -> None:
|
|
36
|
+
def __init__(self, database : str | Path | Literal[":memory:"], **connection_params) -> None:
|
|
31
37
|
|
|
32
38
|
self.database = database
|
|
33
39
|
self.connection_params = connection_params
|
|
@@ -36,18 +42,20 @@ class ConnectionManager:
|
|
|
36
42
|
|
|
37
43
|
|
|
38
44
|
@overload
|
|
39
|
-
def _fetch(
|
|
40
|
-
|
|
45
|
+
def _fetch(
|
|
46
|
+
self, query : str, args : SqlRow, method : Literal["fetchone"]
|
|
47
|
+
) -> FetchRow | None: ...
|
|
41
48
|
@overload
|
|
42
|
-
def _fetch(
|
|
43
|
-
|
|
49
|
+
def _fetch(
|
|
50
|
+
self, query : str, args : SqlRow, method : Literal["fetchall"]
|
|
51
|
+
) -> list[FetchRow]: ...
|
|
44
52
|
|
|
45
53
|
def _fetch(
|
|
46
54
|
self,
|
|
47
55
|
query : str,
|
|
48
56
|
args : SqlRow = (),
|
|
49
57
|
method : Literal["fetchone", "fetchall"] = "fetchall"
|
|
50
|
-
) ->
|
|
58
|
+
) -> FetchRow | list[FetchRow] | None:
|
|
51
59
|
|
|
52
60
|
logger.debug(f"{self.database}: {query} {args}")
|
|
53
61
|
|
|
@@ -117,7 +125,7 @@ class ConnectionManager:
|
|
|
117
125
|
return self._execute(query, args, method="executemany")
|
|
118
126
|
|
|
119
127
|
|
|
120
|
-
def fetchone(self, query : str, *args : SqlValue) ->
|
|
128
|
+
def fetchone(self, query : str, *args : SqlValue) -> FetchRow | None:
|
|
121
129
|
"""
|
|
122
130
|
Fetch first row based on `query`
|
|
123
131
|
|
|
@@ -126,12 +134,12 @@ class ConnectionManager:
|
|
|
126
134
|
*args (tuple[SqlValue, ...]): Arguments to the execution
|
|
127
135
|
|
|
128
136
|
Returns:
|
|
129
|
-
row (
|
|
137
|
+
row (FetchRow | None): Single row
|
|
130
138
|
"""
|
|
131
139
|
return self._fetch(query, args, method="fetchone")
|
|
132
140
|
|
|
133
141
|
|
|
134
|
-
def fetchmany(self, query : str, *args : SqlValue, size : int = 1) -> list[
|
|
142
|
+
def fetchmany(self, query : str, *args : SqlValue, size : int = 1) -> list[FetchRow]:
|
|
135
143
|
"""
|
|
136
144
|
Fetch first `size` rows based on `query`
|
|
137
145
|
|
|
@@ -141,7 +149,7 @@ class ConnectionManager:
|
|
|
141
149
|
size (int): Number of rows to return
|
|
142
150
|
|
|
143
151
|
Returns:
|
|
144
|
-
rows (list[
|
|
152
|
+
rows (list[FetchRow]): list of `size` rows
|
|
145
153
|
"""
|
|
146
154
|
logger.debug(f"{self.database}: {query} {args}")
|
|
147
155
|
|
|
@@ -155,7 +163,7 @@ class ConnectionManager:
|
|
|
155
163
|
return cursor.fetchmany(size)
|
|
156
164
|
|
|
157
165
|
|
|
158
|
-
def fetchall(self, query : str, *args : SqlValue) -> list[
|
|
166
|
+
def fetchall(self, query : str, *args : SqlValue) -> list[FetchRow]:
|
|
159
167
|
"""
|
|
160
168
|
Fetch all rows based on `query`
|
|
161
169
|
|
|
@@ -164,11 +172,79 @@ class ConnectionManager:
|
|
|
164
172
|
*args (tuple[SqlValue, ...]): Arguments to the execution
|
|
165
173
|
|
|
166
174
|
Returns:
|
|
167
|
-
rows (list[
|
|
175
|
+
rows (list[FetchRow]): list of rows
|
|
168
176
|
"""
|
|
169
177
|
return self._fetch(query, args, method="fetchall")
|
|
170
178
|
|
|
171
|
-
|
|
179
|
+
|
|
180
|
+
def first(self, query : str, *args : SqlValue) -> FetchRow:
|
|
181
|
+
"""
|
|
182
|
+
Same as `fetchone` but if query returns `None` - will raise `TableIndexError`
|
|
183
|
+
|
|
184
|
+
Args:
|
|
185
|
+
query (str): SQL query
|
|
186
|
+
*args (tuple[SqlValue, ...]): Arguments to the execution
|
|
187
|
+
|
|
188
|
+
Returns:
|
|
189
|
+
row (FetchRow): Single row
|
|
190
|
+
"""
|
|
191
|
+
if out := self.fetchone(query, *args):
|
|
192
|
+
return out
|
|
193
|
+
|
|
194
|
+
raise TableIndexError("No rows exist for the provided query")
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def one(self, query : str, *args : SqlValue) -> FetchRow:
|
|
198
|
+
"""
|
|
199
|
+
Fetch exactly one row if only one row for this query exists.
|
|
200
|
+
Otherwise, raise `TableIndexError`
|
|
201
|
+
|
|
202
|
+
Args:
|
|
203
|
+
query (str): SQL query
|
|
204
|
+
*args (tuple[SqlValue, ...]): Arguments to the execution
|
|
205
|
+
|
|
206
|
+
Returns:
|
|
207
|
+
row (FetchRow): Single row
|
|
208
|
+
"""
|
|
209
|
+
|
|
210
|
+
out = self.fetchmany(query, *args, size=2)
|
|
211
|
+
|
|
212
|
+
if len(out) != 1:
|
|
213
|
+
raise TableIndexError(
|
|
214
|
+
"Expected exactly one row to be fetched, "
|
|
215
|
+
f"but got {'0' if len(out) < 1 else 'more than 1'}"
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
return out[0]
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@overload
|
|
222
|
+
def scalar(self, query : str, *args : SqlValue) -> Any | None: ...
|
|
223
|
+
@overload
|
|
224
|
+
def scalar[T](self, query : str, *args : SqlValue, default : T) -> Any | T: ...
|
|
225
|
+
|
|
226
|
+
def scalar[T](self, query : str, *args : SqlValue, default : T | None = None) -> Any | T | None:
|
|
227
|
+
"""
|
|
228
|
+
Value of the first column of the first row, or `default`.
|
|
229
|
+
|
|
230
|
+
`default` replaces `None` in both cases where it can occur: when the
|
|
231
|
+
query matches no rows, and when the fetched value itself is `NULL`.
|
|
232
|
+
Other falsy values (`0`, `""`, `False`) are returned as is.
|
|
233
|
+
|
|
234
|
+
Args:
|
|
235
|
+
query (str): SQL query
|
|
236
|
+
*args (tuple[SqlValue, ...]): Arguments to the execution
|
|
237
|
+
default (T): Keyword-only. Value returned instead of `None`. Defaults to `None`
|
|
238
|
+
|
|
239
|
+
Returns:
|
|
240
|
+
scalar (Any | T): First column of the first row, or `default`
|
|
241
|
+
"""
|
|
242
|
+
out = self.fetchone(query, *args)
|
|
243
|
+
value = out[0] if out is not None else None
|
|
244
|
+
|
|
245
|
+
return default if value is None else value
|
|
246
|
+
|
|
247
|
+
|
|
172
248
|
def in_transaction(self) -> bool:
|
|
173
249
|
""" Returns True if instance is in transaction """
|
|
174
250
|
return hasattr(self, "_trans") and hasattr(self, "_trans_cursor")
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
from typing import get_origin, get_args
|
|
2
|
+
|
|
3
|
+
from ..exceptions import TableDeclarationError
|
|
4
|
+
from .types import Primary
|
|
5
|
+
|
|
6
|
+
class SqlTableMeta(type):
|
|
7
|
+
|
|
8
|
+
def __init__(cls, name, bases, namespace, **kwargs):
|
|
9
|
+
super().__init__(name, bases, namespace, **kwargs)
|
|
10
|
+
|
|
11
|
+
if not bases or bases == (object,):
|
|
12
|
+
return
|
|
13
|
+
|
|
14
|
+
annotations = cls.__annotations__
|
|
15
|
+
|
|
16
|
+
tablename = cls.__tablename__ if \
|
|
17
|
+
hasattr(cls, "__tablename__") and cls.__tablename__ is not None\
|
|
18
|
+
else cls.__name__
|
|
19
|
+
|
|
20
|
+
columns = list(getattr(cls, "__columns__", []))
|
|
21
|
+
types = list(getattr(cls, "__types__", []))
|
|
22
|
+
primary = list(getattr(cls, "__primary__", []))
|
|
23
|
+
|
|
24
|
+
for name, type_ in annotations.items():
|
|
25
|
+
if name.startswith("_") or name.endswith("_"):
|
|
26
|
+
continue
|
|
27
|
+
|
|
28
|
+
if name in columns:
|
|
29
|
+
raise TableDeclarationError(f"Annotated column `{name}` is already in __columns__")
|
|
30
|
+
|
|
31
|
+
columns.append(name)
|
|
32
|
+
|
|
33
|
+
if not get_origin(type_) == Primary:
|
|
34
|
+
types.append(type_)
|
|
35
|
+
continue
|
|
36
|
+
|
|
37
|
+
if name in primary:
|
|
38
|
+
raise TableDeclarationError(f"Annotated primary column `{name}` is already in __primary__")
|
|
39
|
+
|
|
40
|
+
primary_type = get_args(type_)[0]
|
|
41
|
+
|
|
42
|
+
if not primary_type:
|
|
43
|
+
raise TableDeclarationError(("Primary type was declared without the type. "
|
|
44
|
+
"Usage: `my_column : Primary[T]`, where T is desired type"))
|
|
45
|
+
|
|
46
|
+
types.append(primary_type)
|
|
47
|
+
primary.append(name)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
cls.__tablename__ = tablename
|
|
51
|
+
cls.__columns__ = columns
|
|
52
|
+
cls.__types__ = types
|
|
53
|
+
cls.__primary__ = primary
|
|
54
|
+
cls._validate_attributes()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _validate_attributes(self) -> None:
|
|
58
|
+
|
|
59
|
+
if self.__tablename__.lower() == "table":
|
|
60
|
+
raise TableDeclarationError(
|
|
61
|
+
"Can't use 'table' as `__tablename__`. It's a restricted syntax word in sql."
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
missing_attrs = [
|
|
65
|
+
attr for attr in
|
|
66
|
+
[ "__columns__", "__types__", "__primary__", "__tablename__"]
|
|
67
|
+
if not hasattr(self, attr)
|
|
68
|
+
]
|
|
69
|
+
|
|
70
|
+
if missing_attrs:
|
|
71
|
+
raise TableDeclarationError(f'{self.__name__} is missing attributes: {missing_attrs}')
|
|
72
|
+
|
|
73
|
+
n_types, n_cols = len(self.__types__), len(self.__columns__)
|
|
74
|
+
|
|
75
|
+
if not n_types == n_cols:
|
|
76
|
+
raise TableDeclarationError((f'`__types__` and `__columns__`: length mismatch: types = {n_types}, columns = {n_cols}'))
|
|
77
|
+
|
|
78
|
+
if len(self.__primary__) < 1:
|
|
79
|
+
raise TableDeclarationError(f'`__primary__`: Number of primary keys must be at least 1')
|
|
80
|
+
|
|
81
|
+
wrong_primaries = [
|
|
82
|
+
prim for prim in self.__primary__ if
|
|
83
|
+
prim not in self.__columns__
|
|
84
|
+
]
|
|
85
|
+
|
|
86
|
+
if wrong_primaries:
|
|
87
|
+
raise TableDeclarationError(f'`__primary__`: Keys {wrong_primaries} can\'t be primaries as they are not declared in __columns__')
|
|
@@ -1,4 +1,37 @@
|
|
|
1
|
-
from typing import Sequence
|
|
1
|
+
from typing import Sequence, Iterable
|
|
2
|
+
|
|
3
|
+
from ..exceptions import SqlEngineError
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def quote(name : str) -> str:
|
|
7
|
+
""" Quotes SQL identifier (table or column name), doubling inner double quotes """
|
|
8
|
+
return '"' + name.replace('"', '""') + '"'
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def resolve_columns(names : Iterable[str], known : Sequence[str]) -> list[str]:
|
|
12
|
+
"""
|
|
13
|
+
Checks that every name in `names` is a column from `known` and returns them
|
|
14
|
+
spelled as declared. Matching is case-insensitive, same as in SQLite.
|
|
15
|
+
|
|
16
|
+
This check is required for quoted names: SQLite treats a double-quoted name
|
|
17
|
+
that matches no column as a string literal, so a typo would silently become
|
|
18
|
+
an always-true or always-false condition instead of an error.
|
|
19
|
+
"""
|
|
20
|
+
canonical = {col.lower() : col for col in known}
|
|
21
|
+
resolved : list[str] = []
|
|
22
|
+
unknown : list[str] = []
|
|
23
|
+
|
|
24
|
+
for name in names:
|
|
25
|
+
col = canonical.get(name.lower())
|
|
26
|
+
if col is None:
|
|
27
|
+
unknown.append(name)
|
|
28
|
+
else:
|
|
29
|
+
resolved.append(col)
|
|
30
|
+
|
|
31
|
+
if unknown:
|
|
32
|
+
raise SqlEngineError(f"Unknown column(s) {unknown}. Available columns: {list(known)}")
|
|
33
|
+
|
|
34
|
+
return resolved
|
|
2
35
|
|
|
3
36
|
|
|
4
37
|
def format_list(items : Sequence | set, brackets : bool = True) -> str:
|
|
@@ -68,6 +101,7 @@ def select(
|
|
|
68
101
|
tablename : str,
|
|
69
102
|
columns : str | list[str] = "*",
|
|
70
103
|
where_clause: str | None = None,
|
|
104
|
+
group_by : str | None = None,
|
|
71
105
|
order_by : str | None = None,
|
|
72
106
|
limit : int | str | None = None
|
|
73
107
|
) -> str:
|
|
@@ -77,6 +111,7 @@ def select(
|
|
|
77
111
|
|
|
78
112
|
query = f"SELECT {_columns} FROM {tablename}"
|
|
79
113
|
query += f" WHERE {where_clause}" if where_clause else ""
|
|
114
|
+
query += f" GROUP BY {group_by}" if group_by else ""
|
|
80
115
|
query += f" ORDER BY {order_by}" if order_by else ""
|
|
81
116
|
query += f" LIMIT {limit}" if limit else ""
|
|
82
117
|
query += ";"
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
from typing import Sequence, Literal, Generator, Self
|
|
1
|
+
from typing import Sequence, Literal, Generator, Self, Any, overload
|
|
2
2
|
from abc import ABC, abstractmethod
|
|
3
3
|
|
|
4
4
|
from . import sqlgen as sql
|
|
5
5
|
from .connection_manager import ConnectionManager
|
|
6
6
|
|
|
7
|
-
from .types import SqlValue,
|
|
7
|
+
from .types import SqlValue, Schema, FetchRow
|
|
8
8
|
from .repr import to_html
|
|
9
9
|
from ..exceptions import SqlEngineError, OutsideTransactionError
|
|
10
10
|
|
|
@@ -229,6 +229,7 @@ class Select(Statement):
|
|
|
229
229
|
|
|
230
230
|
self._columns : list[str] = []
|
|
231
231
|
self._order_by : list[str] = []
|
|
232
|
+
self._group_by : list[str] = []
|
|
232
233
|
self._aggregate : str | None = None
|
|
233
234
|
self._limit : int | None = None
|
|
234
235
|
|
|
@@ -254,37 +255,91 @@ class Select(Statement):
|
|
|
254
255
|
|
|
255
256
|
|
|
256
257
|
def order_by(self, column : str, ascending : bool = True) -> Self:
|
|
257
|
-
"""
|
|
258
|
+
""" Order returned rows by provided column """
|
|
258
259
|
order = "ASC" if ascending else "DESC"
|
|
259
260
|
self._order_by.append(f"{column} {order}")
|
|
260
261
|
return self
|
|
261
262
|
|
|
262
263
|
|
|
264
|
+
def group_by(self, *columns : str) -> Self:
|
|
265
|
+
""" Group by provided columns """
|
|
266
|
+
self._group_by.extend(columns)
|
|
267
|
+
return self
|
|
268
|
+
|
|
269
|
+
|
|
263
270
|
def limit(self, n : int) -> Self:
|
|
264
271
|
""" Limit number of returned rows """
|
|
265
272
|
self._limit = n
|
|
266
273
|
return self
|
|
267
274
|
|
|
268
275
|
|
|
269
|
-
def fetchone(self) ->
|
|
276
|
+
def fetchone(self) -> FetchRow | None:
|
|
270
277
|
""" Fetch first row """
|
|
271
278
|
query, args = self.build()
|
|
272
279
|
return self._connection.fetchone(query, *args)
|
|
273
280
|
|
|
274
281
|
|
|
275
|
-
def fetchmany(self, size : int = 1) -> list[
|
|
282
|
+
def fetchmany(self, size : int = 1) -> list[FetchRow]:
|
|
276
283
|
""" Fetch first `size` rows """
|
|
277
284
|
query, args = self.build()
|
|
278
285
|
return self._connection.fetchmany(query, *args, size=size)
|
|
279
286
|
|
|
280
287
|
|
|
281
|
-
def fetchall(self) -> list[
|
|
288
|
+
def fetchall(self) -> list[FetchRow]:
|
|
282
289
|
""" Fetch all rows """
|
|
283
290
|
query, args = self.build()
|
|
284
291
|
return self._connection.fetchall(query, *args)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def first(self) -> FetchRow:
|
|
295
|
+
""" Same as `fetchone` but if query returns `None` - will raise `TableIndexError` """
|
|
296
|
+
query, args = self.build()
|
|
297
|
+
return self._connection.first(query, *args)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def one(self) -> FetchRow:
|
|
301
|
+
"""
|
|
302
|
+
Fetch exactly one row if only one row for this query exists.
|
|
303
|
+
Otherwise, raise `TableIndexError`
|
|
304
|
+
"""
|
|
305
|
+
query, args = self.build()
|
|
306
|
+
return self._connection.one(query, *args)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
@overload
|
|
310
|
+
def scalar(self) -> Any | None: ...
|
|
311
|
+
@overload
|
|
312
|
+
def scalar[T](self, default : T) -> Any | T: ...
|
|
313
|
+
|
|
314
|
+
def scalar[T](self, default : T | None = None) -> Any | T | None:
|
|
315
|
+
"""
|
|
316
|
+
Value of the first column of the first row, or `default`.
|
|
317
|
+
|
|
318
|
+
`default` replaces `None` in both cases where it can occur: when the
|
|
319
|
+
query matches no rows, and when the fetched value itself is `NULL`.
|
|
320
|
+
Other falsy values (`0`, `""`, `False`) are returned as is.
|
|
321
|
+
|
|
322
|
+
Args:
|
|
323
|
+
default (T): Value returned instead of `None`. Defaults to `None`
|
|
324
|
+
|
|
325
|
+
Returns:
|
|
326
|
+
scalar (Any | T): First column of the first row, or `default`
|
|
327
|
+
|
|
328
|
+
Example:
|
|
329
|
+
|
|
330
|
+
```python
|
|
331
|
+
# Any | None
|
|
332
|
+
n_rows = table.select.aggregate("COUNT").scalar()
|
|
333
|
+
|
|
334
|
+
# Any | float
|
|
335
|
+
top = table.select("Salary").aggregate("MAX").scalar(default=0.0)
|
|
336
|
+
```
|
|
337
|
+
"""
|
|
338
|
+
query, args = self.build()
|
|
339
|
+
return self._connection.scalar(query, *args, default=default)
|
|
285
340
|
|
|
286
341
|
|
|
287
|
-
def fetchmany_iterator(self, batch_size: int) -> Generator[list[
|
|
342
|
+
def fetchmany_iterator(self, batch_size: int) -> Generator[list[FetchRow], None, None]:
|
|
288
343
|
"""
|
|
289
344
|
Yields all rows in batches within a single transaction.
|
|
290
345
|
|
|
@@ -312,7 +367,7 @@ class Select(Statement):
|
|
|
312
367
|
yield batch
|
|
313
368
|
|
|
314
369
|
|
|
315
|
-
def __iter__(self) -> Generator[
|
|
370
|
+
def __iter__(self) -> Generator[FetchRow, None, None]:
|
|
316
371
|
"""
|
|
317
372
|
Select statement rows iterator
|
|
318
373
|
|
|
@@ -340,8 +395,9 @@ class Select(Statement):
|
|
|
340
395
|
|
|
341
396
|
def _build(self, where_clause : str, *args : SqlValue) -> tuple[str, tuple[SqlValue, ...]]:
|
|
342
397
|
|
|
343
|
-
order = sql.format_list(self._order_by, brackets=False)
|
|
344
|
-
|
|
398
|
+
order = sql.format_list(self._order_by, brackets=False) if self._order_by else None
|
|
399
|
+
group = sql.format_list(self._group_by, brackets=False) if self._group_by else None
|
|
400
|
+
columns = sql.format_list(self._columns, brackets=False) if self._columns else None
|
|
345
401
|
|
|
346
402
|
columns = "*" if not columns else columns
|
|
347
403
|
columns = columns if not self._aggregate else f"{self._aggregate}({columns})"
|
|
@@ -353,7 +409,14 @@ class Select(Statement):
|
|
|
353
409
|
else:
|
|
354
410
|
limit = None
|
|
355
411
|
|
|
356
|
-
query = sql.select(
|
|
412
|
+
query = sql.select(
|
|
413
|
+
tablename = self._tableschema["tablename"],
|
|
414
|
+
columns = columns,
|
|
415
|
+
where_clause= where_clause,
|
|
416
|
+
order_by = order,
|
|
417
|
+
group_by = group,
|
|
418
|
+
limit = limit,
|
|
419
|
+
)
|
|
357
420
|
|
|
358
421
|
return query, args
|
|
359
422
|
|
|
@@ -361,6 +424,7 @@ class Select(Statement):
|
|
|
361
424
|
def _reset(self) -> None:
|
|
362
425
|
self._columns = []
|
|
363
426
|
self._order_by = []
|
|
427
|
+
self._group_by = []
|
|
364
428
|
self._aggregate = None
|
|
365
429
|
self._limit = None
|
|
366
430
|
|
|
@@ -421,6 +485,10 @@ class Update(MutationalStatement):
|
|
|
421
485
|
|
|
422
486
|
|
|
423
487
|
def _build(self, where_clause : str, *args : SqlValue) -> tuple[str, tuple[SqlValue, ...]]:
|
|
488
|
+
|
|
489
|
+
if not where_clause:
|
|
490
|
+
raise SqlEngineError("Update statement must have a where clause")
|
|
491
|
+
|
|
424
492
|
set_clause = sql.format_list(self._set_clauses, brackets=False)
|
|
425
493
|
query = f"UPDATE {self._tableschema["tablename"]} SET {set_clause} WHERE {where_clause};"
|
|
426
494
|
return query, (*self._set_args, *args)
|
|
@@ -428,4 +496,5 @@ class Update(MutationalStatement):
|
|
|
428
496
|
|
|
429
497
|
def _reset(self) -> None:
|
|
430
498
|
self._set_clauses = []
|
|
431
|
-
self._set_args = []
|
|
499
|
+
self._set_args = []
|
|
500
|
+
|
|
@@ -1,21 +1,26 @@
|
|
|
1
1
|
import sqlite3
|
|
2
|
+
import warnings
|
|
2
3
|
from typing import Protocol, Self, TypeGuard, TypedDict, Any
|
|
3
4
|
from types import UnionType
|
|
4
5
|
|
|
6
|
+
from .adapters import BOOL_SQL, REGISTRY_MAP
|
|
7
|
+
from ..exceptions import SqlEngineWarning
|
|
8
|
+
|
|
5
9
|
class CustomType(Protocol):
|
|
6
10
|
@classmethod
|
|
7
11
|
def from_sql(cls, sql : bytes) -> Self:
|
|
8
12
|
""" Method that accepts bytes and returns object instance """
|
|
9
13
|
...
|
|
10
|
-
def to_sql(self) ->
|
|
14
|
+
def to_sql(self) -> int | float | str | bytes | None:
|
|
11
15
|
""" Method that converts object instance to native sqlite3 value """
|
|
12
16
|
...
|
|
13
17
|
|
|
14
18
|
|
|
15
19
|
type SqlValue = str | int | float | bytes | None | CustomType
|
|
16
20
|
type SqlRow = tuple[SqlValue, ...]
|
|
17
|
-
type SqlType = type[str | int | float | bytes | CustomType]
|
|
21
|
+
type SqlType = type[str | int | float | bytes | bool | CustomType]
|
|
18
22
|
type ColumnType = SqlType | str | UnionType
|
|
23
|
+
type FetchRow = tuple[Any, ...]
|
|
19
24
|
|
|
20
25
|
|
|
21
26
|
class Schema(TypedDict):
|
|
@@ -41,10 +46,16 @@ _TYPES_MAP : dict[type | UnionType, str] = {
|
|
|
41
46
|
None | bytes : "BLOB",
|
|
42
47
|
}
|
|
43
48
|
|
|
49
|
+
# Common types that would otherwise need CustomType implementation
|
|
50
|
+
_ADAPTERS_MAP : dict[type | UnionType, str] = {
|
|
51
|
+
bool : BOOL_SQL + " NOT NULL",
|
|
52
|
+
None | bool : BOOL_SQL
|
|
53
|
+
}
|
|
54
|
+
|
|
44
55
|
|
|
45
56
|
def is_custom_type(type_: SqlType | UnionType) -> TypeGuard[type[CustomType]]:
|
|
46
57
|
return (
|
|
47
|
-
type_ not in (str, int, float, bytes)
|
|
58
|
+
type_ not in (str, int, float, bytes, bool)
|
|
48
59
|
and isinstance(type_, type)
|
|
49
60
|
and hasattr(type_, "from_sql")
|
|
50
61
|
and hasattr(type_, "to_sql")
|
|
@@ -68,10 +79,14 @@ def register_type(cls : type[CustomType], type_name : str | None = None) -> None
|
|
|
68
79
|
|
|
69
80
|
def pytype_to_sqltype(type_ : type | UnionType) -> str:
|
|
70
81
|
""" Converts python type to sql type """
|
|
71
|
-
if type_
|
|
72
|
-
|
|
82
|
+
if type_ in _TYPES_MAP:
|
|
83
|
+
return _TYPES_MAP[type_]
|
|
84
|
+
|
|
85
|
+
if type_ in _ADAPTERS_MAP:
|
|
86
|
+
return _ADAPTERS_MAP[type_]
|
|
87
|
+
|
|
88
|
+
raise TypeError(f"{type_} is not natively supported by sqlite3, use CustomType protocol")
|
|
73
89
|
|
|
74
|
-
return _TYPES_MAP[type_]
|
|
75
90
|
|
|
76
91
|
|
|
77
92
|
def register_resolve_types(types : list[ColumnType], **connection_params) -> tuple[list[str], dict[str, Any]]:
|
|
@@ -79,6 +94,7 @@ def register_resolve_types(types : list[ColumnType], **connection_params) -> tup
|
|
|
79
94
|
|
|
80
95
|
resolved : list[str] = []
|
|
81
96
|
assert_register_types = False
|
|
97
|
+
params = connection_params.copy()
|
|
82
98
|
|
|
83
99
|
for type_ in types:
|
|
84
100
|
|
|
@@ -91,15 +107,27 @@ def register_resolve_types(types : list[ColumnType], **connection_params) -> tup
|
|
|
91
107
|
|
|
92
108
|
register_type(type_, ctname)
|
|
93
109
|
resolved.append(ctname)
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
110
|
+
assert_register_types = True
|
|
111
|
+
continue
|
|
112
|
+
|
|
113
|
+
if type_ in REGISTRY_MAP:
|
|
114
|
+
REGISTRY_MAP[type_]()
|
|
115
|
+
assert_register_types = True
|
|
116
|
+
|
|
99
117
|
sql_type = pytype_to_sqltype(type_)
|
|
100
118
|
resolved.append(sql_type)
|
|
101
119
|
|
|
102
|
-
if assert_register_types
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
120
|
+
if assert_register_types:
|
|
121
|
+
if "detect_types" not in params:
|
|
122
|
+
params["detect_types"] = sqlite3.PARSE_DECLTYPES
|
|
123
|
+
|
|
124
|
+
elif not params["detect_types"] & sqlite3.PARSE_DECLTYPES:
|
|
125
|
+
warnings.warn(
|
|
126
|
+
"Table declares types that need converters, but the provided `detect_types` "
|
|
127
|
+
"lacks `sqlite3.PARSE_DECLTYPES`: those columns will be returned unconverted. "
|
|
128
|
+
"Add `sqlite3.PARSE_DECLTYPES` to `detect_types` or filter `SqlEngineWarning`.",
|
|
129
|
+
SqlEngineWarning,
|
|
130
|
+
stacklevel=3,
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
return resolved, params
|
|
@@ -17,4 +17,14 @@ class NestedTransactionError(TransactionError):
|
|
|
17
17
|
|
|
18
18
|
class TableDeclarationError(SqlEngineError):
|
|
19
19
|
""" Errors of table declaration """
|
|
20
|
-
pass
|
|
20
|
+
pass
|
|
21
|
+
|
|
22
|
+
class TableIndexError(SqlEngineError, KeyError):
|
|
23
|
+
""" Errors of table index """
|
|
24
|
+
|
|
25
|
+
def __str__(self) -> str:
|
|
26
|
+
return str(self.args[0])
|
|
27
|
+
|
|
28
|
+
class SqlEngineWarning(UserWarning):
|
|
29
|
+
""" Warnings linked to sqlengine module """
|
|
30
|
+
pass
|
|
@@ -30,16 +30,16 @@ def get_database_tablenames(database : str, cursor : sqlite3.Cursor | None = Non
|
|
|
30
30
|
def get_table_schema(database : str, tablename : str, cursor : sqlite3.Cursor | None = None) -> Schema | None:
|
|
31
31
|
""" Constructs `Schema` from provided `database` and `tablename` if this table exists """
|
|
32
32
|
|
|
33
|
-
query =
|
|
33
|
+
query = "SELECT * FROM pragma_table_info(?);"
|
|
34
34
|
|
|
35
35
|
if cursor:
|
|
36
|
-
cursor.execute(query)
|
|
36
|
+
cursor.execute(query, (tablename,))
|
|
37
37
|
column_types = cursor.fetchall()
|
|
38
38
|
|
|
39
39
|
else:
|
|
40
40
|
with sqlite3.connect(database) as conn:
|
|
41
41
|
cur = conn.cursor()
|
|
42
|
-
cur.execute(query)
|
|
42
|
+
cur.execute(query, (tablename,))
|
|
43
43
|
column_types = cur.fetchall()
|
|
44
44
|
|
|
45
45
|
if not column_types:
|
|
@@ -2,24 +2,27 @@ import logging
|
|
|
2
2
|
import os
|
|
3
3
|
import sqlite3
|
|
4
4
|
|
|
5
|
-
from typing
|
|
6
|
-
from typing
|
|
5
|
+
from typing import Sequence, Literal, Any
|
|
6
|
+
from typing import overload
|
|
7
|
+
from pathlib import Path
|
|
7
8
|
|
|
8
|
-
from .exceptions import
|
|
9
|
+
from .exceptions import TableIndexError
|
|
10
|
+
|
|
11
|
+
from ._internal.metaclasses import SqlTableMeta
|
|
9
12
|
|
|
10
13
|
from ._internal import sqlgen as sql
|
|
11
14
|
from ._internal.repr import to_html
|
|
12
15
|
|
|
13
16
|
from ._internal import ConnectionManager, Select, Update, Delete
|
|
14
|
-
from ._internal.types import SqlRow, SqlValue, ColumnType
|
|
15
|
-
from ._internal.types import Schema
|
|
17
|
+
from ._internal.types import FetchRow, SqlRow, SqlValue, ColumnType
|
|
18
|
+
from ._internal.types import Schema
|
|
16
19
|
from ._internal.types import register_resolve_types
|
|
17
20
|
|
|
18
21
|
logger = logging.getLogger("sqlengine")
|
|
19
22
|
logger.setLevel(os.getenv("SQL_ENGINE_LOG_LEVEL", "WARNING").upper())
|
|
20
23
|
|
|
21
24
|
|
|
22
|
-
class SqlTableMixin:
|
|
25
|
+
class SqlTableMixin(metaclass=SqlTableMeta):
|
|
23
26
|
"""
|
|
24
27
|
Lightweight wrapper for SQLite3 tables
|
|
25
28
|
|
|
@@ -57,94 +60,27 @@ class SqlTableMixin:
|
|
|
57
60
|
__types__ : list[ColumnType]
|
|
58
61
|
__primary__ : list[str]
|
|
59
62
|
|
|
60
|
-
def __init__(
|
|
61
|
-
|
|
63
|
+
def __init__(
|
|
64
|
+
self,
|
|
65
|
+
database: str | Path | Literal[":memory:"],
|
|
66
|
+
force_drop : bool = False,
|
|
67
|
+
create : bool = True,
|
|
68
|
+
**connection_params
|
|
69
|
+
) -> None:
|
|
70
|
+
|
|
62
71
|
self.database = database
|
|
63
72
|
|
|
64
|
-
resolved_types, connection_params = register_resolve_types(
|
|
73
|
+
resolved_types, connection_params = register_resolve_types(
|
|
74
|
+
self.__types__, **connection_params
|
|
75
|
+
)
|
|
65
76
|
|
|
66
77
|
self._connection_manager = ConnectionManager(database, **connection_params)
|
|
67
78
|
self.__types_sql__ = resolved_types
|
|
68
79
|
|
|
69
|
-
self._write_db(force_drop)
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
def __init_subclass__(cls) -> None:
|
|
73
|
-
|
|
74
|
-
annotations = get_type_hints(cls)
|
|
75
|
-
|
|
76
|
-
tablename = cls.__tablename__ if \
|
|
77
|
-
hasattr(cls, "__tablename__") and cls.__tablename__ is not None\
|
|
78
|
-
else cls.__name__
|
|
79
|
-
|
|
80
|
-
columns = cls.__columns__ if hasattr(cls, "__columns__") else []
|
|
81
|
-
types = cls.__types__ if hasattr(cls, "__types__") else []
|
|
82
|
-
primary = cls.__primary__ if hasattr(cls, "__primary__") else []
|
|
83
|
-
|
|
84
|
-
for name, type_ in annotations.items():
|
|
85
|
-
if name.startswith("_") or name.endswith("_"):
|
|
86
|
-
continue
|
|
87
|
-
|
|
88
|
-
if name in columns:
|
|
89
|
-
raise TableDeclarationError(f"Annotated column `{name}` is already in __columns__")
|
|
90
|
-
|
|
91
|
-
columns.append(name)
|
|
92
|
-
|
|
93
|
-
if not get_origin(type_) == Primary:
|
|
94
|
-
types.append(type_)
|
|
95
|
-
continue
|
|
96
|
-
|
|
97
|
-
if name in primary:
|
|
98
|
-
raise TableDeclarationError(f"Annotated primary column `{name}` is already in __primary__")
|
|
99
|
-
|
|
100
|
-
primary_type = get_args(type_)[0]
|
|
101
|
-
|
|
102
|
-
if not primary_type:
|
|
103
|
-
raise TableDeclarationError(("Primary type was declared without the type. "
|
|
104
|
-
"Usage: `my_column : Primary[T]`, where T is desired type"))
|
|
105
|
-
|
|
106
|
-
types.append(primary_type)
|
|
107
|
-
primary.append(name)
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
cls.__tablename__ = tablename
|
|
111
|
-
|
|
112
|
-
cls.__columns__ = columns
|
|
113
|
-
cls.__types__ = types
|
|
114
|
-
cls.__primary__ = primary
|
|
115
|
-
cls._validate_attributes()
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
@classmethod
|
|
119
|
-
def _validate_attributes(cls) -> None:
|
|
120
|
-
|
|
121
|
-
missing_attrs = [
|
|
122
|
-
attr for attr in
|
|
123
|
-
[ "__columns__", "__types__", "__primary__", "__tablename__"]
|
|
124
|
-
if not hasattr(cls, attr)
|
|
125
|
-
]
|
|
126
|
-
|
|
127
|
-
if missing_attrs:
|
|
128
|
-
raise TableDeclarationError(f'{cls.__name__} is missing attributes: {missing_attrs}')
|
|
129
|
-
|
|
130
|
-
n_types, n_cols = len(cls.__types__), len(cls.__columns__)
|
|
80
|
+
self._write_db(force_drop, create)
|
|
131
81
|
|
|
132
|
-
if not n_types == n_cols:
|
|
133
|
-
raise TableDeclarationError((f'`__types__` and `__columns__`: length mismatch: types = {n_types}, columns = {n_cols}'))
|
|
134
|
-
|
|
135
|
-
if len(cls.__primary__) < 1:
|
|
136
|
-
raise TableDeclarationError(f'`__primary__`: Number of primary keys must be at least 1')
|
|
137
|
-
|
|
138
|
-
wrong_primaries = [
|
|
139
|
-
prim for prim in cls.__primary__ if
|
|
140
|
-
prim not in cls.__columns__
|
|
141
|
-
]
|
|
142
|
-
|
|
143
|
-
if wrong_primaries:
|
|
144
|
-
raise TableDeclarationError(f'`__primary__`: Keys {wrong_primaries} can\'t be primaries as they are not declared in __columns__')
|
|
145
|
-
|
|
146
82
|
|
|
147
|
-
def _write_db(self, force_drop : bool) -> None:
|
|
83
|
+
def _write_db(self, force_drop : bool, create : bool) -> None:
|
|
148
84
|
|
|
149
85
|
if self.database == ":memory:":
|
|
150
86
|
logger.debug(f"{self.tablename}: Using in-memory database")
|
|
@@ -152,14 +88,15 @@ class SqlTableMixin:
|
|
|
152
88
|
|
|
153
89
|
if not os.path.exists(self.database):
|
|
154
90
|
logger.debug(f'{self.tablename}: {self.database} does not exist. Creating...')
|
|
155
|
-
parent_dir = self.database.removesuffix(os.path.basename(self.database))
|
|
91
|
+
parent_dir = str(self.database).removesuffix(os.path.basename(self.database))
|
|
156
92
|
if parent_dir:
|
|
157
93
|
os.makedirs(parent_dir, exist_ok=True)
|
|
158
94
|
|
|
159
95
|
elif force_drop is True:
|
|
160
96
|
self.drop_table(confirm=True)
|
|
161
97
|
|
|
162
|
-
|
|
98
|
+
if create:
|
|
99
|
+
self.create_table()
|
|
163
100
|
|
|
164
101
|
|
|
165
102
|
def create_table(self) -> None:
|
|
@@ -219,7 +156,7 @@ class SqlTableMixin:
|
|
|
219
156
|
```
|
|
220
157
|
"""
|
|
221
158
|
columns = self.columns[:len(args)]
|
|
222
|
-
columns.extend(kwargs.keys())
|
|
159
|
+
columns.extend(sql.resolve_columns(kwargs.keys(), self.columns))
|
|
223
160
|
query = sql.insert_row(self.tablename, columns)
|
|
224
161
|
self._connection_manager.execute(query, *args, *kwargs.values())
|
|
225
162
|
|
|
@@ -243,7 +180,7 @@ class SqlTableMixin:
|
|
|
243
180
|
```
|
|
244
181
|
"""
|
|
245
182
|
columns = self.columns[:len(args)]
|
|
246
|
-
columns.extend(kwargs.keys())
|
|
183
|
+
columns.extend(sql.resolve_columns(kwargs.keys(), self.columns))
|
|
247
184
|
query = sql.upsert(self.tablename, columns, self.primary)
|
|
248
185
|
self._connection_manager.execute(query, *args, *kwargs.values())
|
|
249
186
|
|
|
@@ -314,25 +251,24 @@ class SqlTableMixin:
|
|
|
314
251
|
|
|
315
252
|
|
|
316
253
|
def __len__(self) -> int:
|
|
317
|
-
|
|
318
|
-
length = self.select.aggregate("COUNT").fetchone()[0]
|
|
319
|
-
|
|
320
|
-
if not isinstance(length, int):
|
|
321
|
-
raise ValueError("Unreachable")
|
|
322
|
-
|
|
323
|
-
return length
|
|
254
|
+
return self.select.aggregate("COUNT").scalar(default=0)
|
|
324
255
|
|
|
325
256
|
|
|
326
257
|
@overload
|
|
327
|
-
def __getitem__(self, key : tuple[SqlValue, ...] | SqlValue) ->
|
|
258
|
+
def __getitem__(self, key : tuple[SqlValue, ...] | SqlValue) -> FetchRow: ...
|
|
328
259
|
@overload
|
|
329
|
-
def __getitem__(self, key : slice) -> list[
|
|
260
|
+
def __getitem__(self, key : slice) -> list[FetchRow]: ...
|
|
330
261
|
|
|
331
|
-
def __getitem__(
|
|
262
|
+
def __getitem__(
|
|
263
|
+
self, key : tuple[SqlValue, ...] | SqlValue | slice
|
|
264
|
+
) -> FetchRow | list[FetchRow]:
|
|
332
265
|
""" Get row by primary key """
|
|
333
266
|
|
|
334
267
|
if len(self.primary) > 1 and not (isinstance(key, tuple) and len(key) == len(self.primary)):
|
|
335
|
-
raise
|
|
268
|
+
raise TableIndexError(
|
|
269
|
+
"`key` expected to be a tuple of equal legth to "
|
|
270
|
+
"`primary` for multi index tables"
|
|
271
|
+
)
|
|
336
272
|
|
|
337
273
|
select = self.select
|
|
338
274
|
|
|
@@ -342,13 +278,13 @@ class SqlTableMixin:
|
|
|
342
278
|
primary = self.primary[0]
|
|
343
279
|
|
|
344
280
|
if key.start is None:
|
|
345
|
-
start = select(primary).aggregate('MIN').
|
|
281
|
+
start = select(primary).aggregate('MIN').scalar(default=0)
|
|
346
282
|
select.reset()
|
|
347
283
|
else:
|
|
348
284
|
start = key.start
|
|
349
285
|
|
|
350
286
|
if key.stop is None:
|
|
351
|
-
stop = select(primary).aggregate('MAX').
|
|
287
|
+
stop = select(primary).aggregate('MAX').scalar(default=0)
|
|
352
288
|
select.reset()
|
|
353
289
|
else:
|
|
354
290
|
stop = key.stop
|
|
@@ -359,7 +295,10 @@ class SqlTableMixin:
|
|
|
359
295
|
step = key.step
|
|
360
296
|
|
|
361
297
|
if not (isinstance(start, int) and isinstance(stop, int)):
|
|
362
|
-
raise
|
|
298
|
+
raise TableIndexError(
|
|
299
|
+
"Looks like like `primary` key "
|
|
300
|
+
"is not integer type, or you passed non-integer slice"
|
|
301
|
+
)
|
|
363
302
|
|
|
364
303
|
return start, stop, step
|
|
365
304
|
|
|
@@ -386,10 +325,22 @@ class SqlTableMixin:
|
|
|
386
325
|
|
|
387
326
|
for col, val in zip(self.primary, key):
|
|
388
327
|
select.where.eq(col, val)
|
|
389
|
-
|
|
328
|
+
|
|
329
|
+
out = select.fetchone()
|
|
330
|
+
|
|
331
|
+
if out is None:
|
|
332
|
+
raise TableIndexError(f"Key `{key}` is not in the table index")
|
|
333
|
+
|
|
334
|
+
return out
|
|
390
335
|
|
|
391
336
|
select.where.eq(self.primary[0], key)
|
|
392
|
-
|
|
337
|
+
|
|
338
|
+
out = select.fetchone()
|
|
339
|
+
|
|
340
|
+
if out is None:
|
|
341
|
+
raise TableIndexError(f"Key `{key}` is not in the table index")
|
|
342
|
+
|
|
343
|
+
return out
|
|
393
344
|
|
|
394
345
|
|
|
395
346
|
@property
|
|
@@ -428,7 +379,7 @@ class SqlTableMixin:
|
|
|
428
379
|
Example:
|
|
429
380
|
|
|
430
381
|
```python
|
|
431
|
-
table.select("Email").where.eq("SupportRepId", 3).then.aggregate("COUNT").
|
|
382
|
+
table.select("Email").where.eq("SupportRepId", 3).then.aggregate("COUNT").scalar()
|
|
432
383
|
```
|
|
433
384
|
"""
|
|
434
385
|
return Select(self.conn, self.schema)
|
|
@@ -2,6 +2,7 @@ import logging
|
|
|
2
2
|
import os
|
|
3
3
|
import sqlite3
|
|
4
4
|
|
|
5
|
+
from pathlib import Path
|
|
5
6
|
from contextlib import contextmanager
|
|
6
7
|
|
|
7
8
|
from ..sqltable import SqlTableMixin
|
|
@@ -44,7 +45,7 @@ def shared_connection(*args : SqlTableMixin, autocommit : bool = True, **connect
|
|
|
44
45
|
raise NestedTransactionError(f"Tables {tables_in_trans} are already in transaction")
|
|
45
46
|
|
|
46
47
|
unique_databases = set(table.database for table in args)
|
|
47
|
-
database_map : dict[str, list[ConnectionManager]] = {}
|
|
48
|
+
database_map : dict[str | Path, list[ConnectionManager]] = {}
|
|
48
49
|
|
|
49
50
|
for db in unique_databases:
|
|
50
51
|
database_map[db] = [table.conn for table in args if table.database == db]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: sqlengine-lite
|
|
3
|
-
Version: 2.2.
|
|
3
|
+
Version: 2.2.4
|
|
4
4
|
Summary: Cute sqlite3 wrapper for sql tables
|
|
5
5
|
Project-URL: Homepage, https://github.com/suffermuffin/SQL-Engine
|
|
6
6
|
Project-URL: Repository, https://github.com/suffermuffin/SQL-Engine.git
|
|
@@ -69,7 +69,18 @@ table.select("InvoiceId", "CustomerId", "BillingAddress", "BillingCountry", "Tot
|
|
|
69
69
|
|
|
70
70
|
## Purpose
|
|
71
71
|
|
|
72
|
-
It's a tiny little modern ORM-like that lets you prototype your databases locally with great flexibility. Also, it can be used in production apps to store and retrieve data, because all select, update, delete queries are parametrized. But it does not restrict you from using your own queries which might not be parameterized with methods like `select.
|
|
72
|
+
It's a tiny little modern ORM-like that lets you prototype your databases locally with great flexibility. Also, it can be used in production apps to store and retrieve data, because all **values** in select, update, delete and insert queries are parametrized. But it does not restrict you from using your own queries which might not be parameterized with methods like `select.custom_query()` and `where.custom()`. Flexibility is a go to for this library.
|
|
73
|
+
|
|
74
|
+
> [!WARNING]
|
|
75
|
+
> **Column names are raw SQL.** Values are always passed as parameters, but column names and expressions given as strings are inserted into the query exactly as written. That is what lets you write `select("COUNT(x)")` or `order_by("Salary * 2")`, but it also means that such strings must never come from user input, or it opens the way to SQL injection:
|
|
76
|
+
>
|
|
77
|
+
> ```py
|
|
78
|
+
> table.select("Name").where.eq("ID", user_input) # safe, value is a parameter
|
|
79
|
+
> table.select("Name").where.eq(user_input, 5) # unsafe, column name is raw SQL
|
|
80
|
+
> table.select("Name").order_by(request.args["sort"]) # unsafe
|
|
81
|
+
> ```
|
|
82
|
+
>
|
|
83
|
+
> If a column name has to depend on user input, check it against `table.columns` first.
|
|
73
84
|
|
|
74
85
|
And last (but not least) is data inspection. If you need to quickly inspect existing .db file but don't want to install yet another heavy ORM with a lot of unused dependencies and features, you might look into SqlEngine, as it uses only native python modules, implements dynamic schema builder and has a good synergy with Jupyter Notebook.
|
|
75
86
|
|
|
@@ -6,7 +6,9 @@ src/sqlengine/exceptions.py
|
|
|
6
6
|
src/sqlengine/schema.py
|
|
7
7
|
src/sqlengine/sqltable.py
|
|
8
8
|
src/sqlengine/_internal/__init__.py
|
|
9
|
+
src/sqlengine/_internal/adapters.py
|
|
9
10
|
src/sqlengine/_internal/connection_manager.py
|
|
11
|
+
src/sqlengine/_internal/metaclasses.py
|
|
10
12
|
src/sqlengine/_internal/repr.py
|
|
11
13
|
src/sqlengine/_internal/sqlgen.py
|
|
12
14
|
src/sqlengine/_internal/statements.py
|
|
@@ -477,7 +477,9 @@ class TestSqlTable(unittest.TestCase):
|
|
|
477
477
|
table.delete.where.eq("ID", 0).then.execute()
|
|
478
478
|
length_after = len(table)
|
|
479
479
|
self.assertEqual(lenght_init - 1, length_after)
|
|
480
|
-
|
|
480
|
+
|
|
481
|
+
with self.assertRaises(exceptions.TableIndexError):
|
|
482
|
+
table[0]
|
|
481
483
|
|
|
482
484
|
|
|
483
485
|
def test_multiple_statements(self):
|
|
@@ -694,8 +696,8 @@ class TestSqlTable(unittest.TestCase):
|
|
|
694
696
|
|
|
695
697
|
self.assertEqual(len(table), 1)
|
|
696
698
|
|
|
697
|
-
dt = table.select("time_at").
|
|
698
|
-
|
|
699
|
+
dt = table.select("time_at").scalar()
|
|
700
|
+
|
|
699
701
|
self.assertIsInstance(dt, DateTime)
|
|
700
702
|
|
|
701
703
|
|
|
@@ -955,25 +957,18 @@ class TestSqlTable(unittest.TestCase):
|
|
|
955
957
|
table = self.empl_table
|
|
956
958
|
table.insert_many(EMPLOYEES_DATA)
|
|
957
959
|
|
|
958
|
-
# COUNT
|
|
959
|
-
count = table.select.aggregate("COUNT").fetchone()[0]
|
|
960
|
-
self.assertEqual(count, len(EMPLOYEES_DATA))
|
|
961
|
-
|
|
962
|
-
# SUM
|
|
963
|
-
total_salary = table.select("salary").aggregate("SUM").fetchone()[0]
|
|
964
960
|
expected_sum = sum(row[3] for row in EMPLOYEES_DATA)
|
|
965
961
|
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
962
|
+
count = table.select.aggregate("COUNT").scalar()
|
|
963
|
+
total = table.select("salary").aggregate("SUM").scalar()
|
|
964
|
+
avg = table.select("salary").aggregate("AVG").scalar()
|
|
965
|
+
min_ = table.select("salary").aggregate("MIN").scalar()
|
|
966
|
+
max_ = table.select("salary").aggregate("MAX").scalar()
|
|
969
967
|
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
max_ = table.select("salary").aggregate("MAX").fetchone()[0]
|
|
974
|
-
|
|
968
|
+
self.assertEqual(count, len(EMPLOYEES_DATA))
|
|
969
|
+
assert isinstance(total, float)
|
|
970
|
+
self.assertAlmostEqual(total, expected_sum)
|
|
975
971
|
assert isinstance(avg, float)
|
|
976
|
-
|
|
977
972
|
self.assertAlmostEqual(avg, expected_sum / len(EMPLOYEES_DATA))
|
|
978
973
|
self.assertEqual(min_, 100.0)
|
|
979
974
|
self.assertEqual(max_, 144.4)
|
|
@@ -982,7 +977,88 @@ class TestSqlTable(unittest.TestCase):
|
|
|
982
977
|
with self.assertRaises(exceptions.SqlEngineError):
|
|
983
978
|
table.select.aggregate("COUNT").aggregate("SUM")
|
|
984
979
|
|
|
985
|
-
|
|
980
|
+
|
|
981
|
+
def test_select_first(self):
|
|
982
|
+
table = self.coord_table
|
|
983
|
+
|
|
984
|
+
# no rows
|
|
985
|
+
with self.assertRaises(exceptions.TableIndexError):
|
|
986
|
+
table.select.first()
|
|
987
|
+
|
|
988
|
+
table.insert_many(COORDS_DATA)
|
|
989
|
+
|
|
990
|
+
# exactly one match
|
|
991
|
+
row = table.select("ID", "name").where.eq("ID", 3).then.first()
|
|
992
|
+
self.assertEqual(row, (3, "loc3"))
|
|
993
|
+
|
|
994
|
+
# several matches: returns the first one in query order
|
|
995
|
+
row = table.select("ID").where.eq("name", "loc0").then.order_by("ID", ascending=False).first()
|
|
996
|
+
self.assertEqual(row, (2,))
|
|
997
|
+
|
|
998
|
+
# no match
|
|
999
|
+
with self.assertRaises(exceptions.TableIndexError):
|
|
1000
|
+
table.select.where.eq("ID", 999).then.first()
|
|
1001
|
+
|
|
1002
|
+
|
|
1003
|
+
def test_select_one(self):
|
|
1004
|
+
table = self.coord_table
|
|
1005
|
+
|
|
1006
|
+
# no rows
|
|
1007
|
+
with self.assertRaises(exceptions.TableIndexError):
|
|
1008
|
+
table.select.one()
|
|
1009
|
+
|
|
1010
|
+
table.insert_many(COORDS_DATA)
|
|
1011
|
+
|
|
1012
|
+
# exactly one match
|
|
1013
|
+
row = table.select("ID", "name").where.eq("ID", 3).then.one()
|
|
1014
|
+
self.assertEqual(row, (3, "loc3"))
|
|
1015
|
+
|
|
1016
|
+
# several matches ("loc0" is used by IDs 0 and 2)
|
|
1017
|
+
with self.assertRaises(exceptions.TableIndexError):
|
|
1018
|
+
table.select.where.eq("name", "loc0").then.one()
|
|
1019
|
+
|
|
1020
|
+
# no match
|
|
1021
|
+
with self.assertRaises(exceptions.TableIndexError):
|
|
1022
|
+
table.select.where.eq("ID", 999).then.one()
|
|
1023
|
+
|
|
1024
|
+
# inside a transaction
|
|
1025
|
+
with table.transaction():
|
|
1026
|
+
row = table.select("ID").where.eq("ID", 5).then.one()
|
|
1027
|
+
self.assertEqual(row, (5,))
|
|
1028
|
+
|
|
1029
|
+
with self.assertRaises(exceptions.TableIndexError):
|
|
1030
|
+
table.select.where.eq("name", "loc0").then.one()
|
|
1031
|
+
|
|
1032
|
+
|
|
1033
|
+
def test_select_scalar(self):
|
|
1034
|
+
table = self.coord_table
|
|
1035
|
+
|
|
1036
|
+
# no rows
|
|
1037
|
+
self.assertIsNone(table.select("temp").scalar())
|
|
1038
|
+
self.assertEqual(table.select("temp").scalar(default=-1.0), -1.0)
|
|
1039
|
+
self.assertEqual(table.select("temp").scalar(-1.0), -1.0)
|
|
1040
|
+
|
|
1041
|
+
# aggregates on an empty table
|
|
1042
|
+
self.assertEqual(table.select.aggregate("COUNT").scalar(), 0)
|
|
1043
|
+
self.assertIsNone(table.select("temp").aggregate("MAX").scalar())
|
|
1044
|
+
self.assertEqual(table.select("temp").aggregate("MAX").scalar(default=0.0), 0.0)
|
|
1045
|
+
self.assertEqual(len(table), 0)
|
|
1046
|
+
|
|
1047
|
+
table.insert_many(COORDS_DATA)
|
|
1048
|
+
table.insert(11, None, Point(11, 11), 11.11)
|
|
1049
|
+
|
|
1050
|
+
# first column of the first row
|
|
1051
|
+
self.assertEqual(table.select("name", "temp").where.eq("ID", 3).then.scalar(), "loc3")
|
|
1052
|
+
self.assertEqual(table.select("temp").order_by("temp", ascending=False).scalar(), 11.11)
|
|
1053
|
+
|
|
1054
|
+
# NULL value is replaced by default, same as a missing row
|
|
1055
|
+
self.assertIsNone(table.select("name").where.eq("ID", 11).then.scalar())
|
|
1056
|
+
self.assertEqual(table.select("name").where.eq("ID", 11).then.scalar(default="n/a"), "n/a")
|
|
1057
|
+
|
|
1058
|
+
# falsy values are kept as is (ID 0 has temp 0.0)
|
|
1059
|
+
self.assertEqual(table.select("temp").where.eq("ID", 0).then.scalar(default=-1.0), 0.0)
|
|
1060
|
+
|
|
1061
|
+
|
|
986
1062
|
def test_select_fetchmany_and_iterator(self):
|
|
987
1063
|
table = self.coord_table
|
|
988
1064
|
table.insert_many(COORDS_DATA)
|
|
@@ -1028,8 +1104,8 @@ class TestSqlTable(unittest.TestCase):
|
|
|
1028
1104
|
table.insert_many(COORDS_DATA)
|
|
1029
1105
|
|
|
1030
1106
|
table.update.set("temp", 99.9).where.eq("ID", 2).then.execute()
|
|
1031
|
-
|
|
1032
|
-
self.assertEqual(
|
|
1107
|
+
temp = table.select("temp").where.eq("ID", 2).then.scalar()
|
|
1108
|
+
self.assertEqual(temp, 99.9)
|
|
1033
1109
|
|
|
1034
1110
|
table.update.set("name", "updated").where.in_("ID", [0, 3, 5]).then.execute()
|
|
1035
1111
|
rows = table.select("name").where.in_("ID", [0,3,5]).then.fetchall()
|
|
@@ -1044,7 +1120,9 @@ class TestSqlTable(unittest.TestCase):
|
|
|
1044
1120
|
|
|
1045
1121
|
table.delete.where.eq("ID", 7).then.execute()
|
|
1046
1122
|
self.assertEqual(len(table), initial_len - 1)
|
|
1047
|
-
|
|
1123
|
+
|
|
1124
|
+
with self.assertRaises(exceptions.TableIndexError):
|
|
1125
|
+
table[7]
|
|
1048
1126
|
|
|
1049
1127
|
# Can't delete without where
|
|
1050
1128
|
with self.assertRaises(exceptions.SqlEngineError):
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{sqlengine_lite-2.2.2 → sqlengine_lite-2.2.4}/src/sqlengine_lite.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
|
File without changes
|