sqlengine-lite 2.2.2__py3-none-any.whl → 2.2.4__py3-none-any.whl

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.
@@ -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 TransactionError, NestedTransactionError, OutsideTransactionError
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(self, query : str, args : SqlRow,
40
- method : Literal["fetchone"]) -> SqlRow: ...
45
+ def _fetch(
46
+ self, query : str, args : SqlRow, method : Literal["fetchone"]
47
+ ) -> FetchRow | None: ...
41
48
  @overload
42
- def _fetch(self, query : str, args : SqlRow,
43
- method : Literal["fetchall"]) -> list[SqlRow]: ...
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
- ) -> SqlRow | list[SqlRow]:
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) -> SqlRow:
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 (SqlRow): Single 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[SqlRow]:
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[SqlRow]): list of `size` rows
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[SqlRow]:
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[SqlRow]): list of rows
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, SqlRow, Schema
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
- """ Orders returned rows by provided column """
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) -> SqlRow:
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[SqlRow]:
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[SqlRow]:
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[SqlRow], None, None]:
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[SqlRow, None, None]:
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
- columns = sql.format_list(self._columns, brackets=False)
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(self._tableschema["tablename"], columns, where_clause, order, limit)
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) -> str | int | float | str | bytes | None:
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_ not in _TYPES_MAP:
72
- raise TypeError(f"{type_} is not natively supported by sqlite3")
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
- if not assert_register_types:
96
- assert_register_types = True
97
- continue
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 and ("detect_types" not in connection_params):
103
- connection_params.update(dict(detect_types=sqlite3.PARSE_DECLTYPES))
104
-
105
- return resolved, connection_params
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
sqlengine/exceptions.py CHANGED
@@ -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
sqlengine/schema.py CHANGED
@@ -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 = f"PRAGMA table_info({tablename});"
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:
sqlengine/sqltable.py CHANGED
@@ -2,24 +2,27 @@ import logging
2
2
  import os
3
3
  import sqlite3
4
4
 
5
- from typing import Sequence, Literal, Any
6
- from typing import get_origin, get_args, overload, get_type_hints
5
+ from typing import Sequence, Literal, Any
6
+ from typing import overload
7
+ from pathlib import Path
7
8
 
8
- from .exceptions import TableDeclarationError
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, Primary
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__(self, database: str | Literal[":memory:"], force_drop : bool = False, **connection_params) -> None:
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(self.__types__, **connection_params)
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
- self.create_table()
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) -> SqlRow: ...
258
+ def __getitem__(self, key : tuple[SqlValue, ...] | SqlValue) -> FetchRow: ...
328
259
  @overload
329
- def __getitem__(self, key : slice) -> list[SqlRow]: ...
260
+ def __getitem__(self, key : slice) -> list[FetchRow]: ...
330
261
 
331
- def __getitem__(self, key : tuple[SqlValue, ...] | SqlValue | slice ) -> SqlRow | list[SqlRow]:
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 IndexError("`key` expected to be a tuple of equal leght to `primary` for multi index tables")
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').fetchone()[0] or 0
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').fetchone()[0] or 0
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 IndexError("Looks like like `primary` key is not integer type, or you passed non-integer slice")
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
- return select.fetchone()
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
- return select.fetchone()
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").fetchone()
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.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.custom()` and `where.custom()`. Flexibility is a go to for this library.
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
 
@@ -0,0 +1,20 @@
1
+ sqlengine/__init__.py,sha256=_t3mutixVp60g1MwD6BZ6WcvXZPFz7JkV29nXXl1bOw,305
2
+ sqlengine/exceptions.py,sha256=EdNA2INeACpuC1Q8eeN7S37sq39KFPI49sB-SOfXH9c,750
3
+ sqlengine/schema.py,sha256=otUeVQsefW5C6qI3x-N--qkV09lVs-ncwb2yNd4QSoo,3624
4
+ sqlengine/sqltable.py,sha256=cYvwDIQ5vHRtdzgHOAktZjNJSlE8OR9YWvDuKkZ8BFI,14066
5
+ sqlengine/_internal/__init__.py,sha256=9cQIPDgLssRJNeROpuDYA0rJzY9B_N9VsY4rJbgzBnk,159
6
+ sqlengine/_internal/adapters.py,sha256=81oQSb1v5Mz0oZzz2EFsePK87aKanzVDZicV8RCEIlQ,252
7
+ sqlengine/_internal/connection_manager.py,sha256=MHGtFBpq5vFsrhnZ3XZi1lxSnatYQbzWVY9pbKVeN5Q,10883
8
+ sqlengine/_internal/metaclasses.py,sha256=DpupziFwz6CORgHPpA4c2Qd907AcEh3g_lSW59XtXQM,3069
9
+ sqlengine/_internal/repr.py,sha256=PEwC3MdOoTE8ORvcVXTCmY502boJfr5V2LU5jJ6qWG0,1478
10
+ sqlengine/_internal/sqlgen.py,sha256=EI30ip0qdtjAm-nJBq5haHsSjm_tfm3ENeq-0avEFzk,4694
11
+ sqlengine/_internal/statements.py,sha256=gilhbLlXciZCY6xkzQk6dj8yAMI6UiFYoyorgz2sqco,15080
12
+ sqlengine/_internal/types.py,sha256=4A25OiSi76RPVasReMsd8hyeg7rJblgHBT93gXEae48,4188
13
+ sqlengine/utils/__init__.py,sha256=EGg576qs61VsXlXd1bxF0oDytlmpcgqouVLdPxwqTrI,173
14
+ sqlengine/utils/connection.py,sha256=x6ssa6x7hNiyEL4L5zshIIQ9B7ZgkIli8w1qxzGnPkw,3150
15
+ sqlengine/utils/convert.py,sha256=8bUNdxNNNkBnUIcTNkLGqA9h_X-D8BHtssHhe0UMPx0,3782
16
+ sqlengine_lite-2.2.4.dist-info/licenses/LICENSE,sha256=aepvve4t1ho5uHMQG88dErp5L5CgoNAXctIjMdoceqY,1069
17
+ sqlengine_lite-2.2.4.dist-info/METADATA,sha256=N3R-B6Nf_IxCkTBXQt2GxXBXosWfsmZ0i92BxS5lT-M,23334
18
+ sqlengine_lite-2.2.4.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
19
+ sqlengine_lite-2.2.4.dist-info/top_level.txt,sha256=KG_FG0LCB_mIEu2qJ5LGLQMpan4QmF5d8xLEcqTghCE,10
20
+ sqlengine_lite-2.2.4.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (82.0.1)
2
+ Generator: setuptools (84.2.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,18 +0,0 @@
1
- sqlengine/__init__.py,sha256=_t3mutixVp60g1MwD6BZ6WcvXZPFz7JkV29nXXl1bOw,305
2
- sqlengine/exceptions.py,sha256=Sd12r8dHgtKr6RKUaiHNhaEpdJr3Jr-JXePwrBQojC4,506
3
- sqlengine/schema.py,sha256=SL-7eXib56wIVHSgykqMJKZGRPJuOffpwA0GJEgChSc,3593
4
- sqlengine/sqltable.py,sha256=ZgkPQi5L1IGHauamTSjqyKVGNMKHCKmt3tEGTI-pCnY,16197
5
- sqlengine/_internal/__init__.py,sha256=9cQIPDgLssRJNeROpuDYA0rJzY9B_N9VsY4rJbgzBnk,159
6
- sqlengine/_internal/connection_manager.py,sha256=j4H7BiPu7iUxqOSRMmApgGnCY9dRBdL4javwMwAi_BU,8522
7
- sqlengine/_internal/repr.py,sha256=PEwC3MdOoTE8ORvcVXTCmY502boJfr5V2LU5jJ6qWG0,1478
8
- sqlengine/_internal/sqlgen.py,sha256=b8usEqBAX5JDEdMR6Xeaona0ZuOi7vtptl858qXhD78,3473
9
- sqlengine/_internal/statements.py,sha256=8D6uZCwm4iMwfq0Lzg5-Z91x68xN874xQbHyZyFPBKE,12876
10
- sqlengine/_internal/types.py,sha256=bA-tsS8r13pvRB3M13wFNsd3Fc9KAaqGW47aXhkKkDQ,3265
11
- sqlengine/utils/__init__.py,sha256=EGg576qs61VsXlXd1bxF0oDytlmpcgqouVLdPxwqTrI,173
12
- sqlengine/utils/connection.py,sha256=wnA21QCUd7meRHL114ZzghchNIgvmq-cEmIJ-8L_ozQ,3118
13
- sqlengine/utils/convert.py,sha256=8bUNdxNNNkBnUIcTNkLGqA9h_X-D8BHtssHhe0UMPx0,3782
14
- sqlengine_lite-2.2.2.dist-info/licenses/LICENSE,sha256=aepvve4t1ho5uHMQG88dErp5L5CgoNAXctIjMdoceqY,1069
15
- sqlengine_lite-2.2.2.dist-info/METADATA,sha256=2WfgmOiu-lq7b6fBamCTtVhuVmYNHwCDuujYz1H9WL0,22586
16
- sqlengine_lite-2.2.2.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
17
- sqlengine_lite-2.2.2.dist-info/top_level.txt,sha256=KG_FG0LCB_mIEu2qJ5LGLQMpan4QmF5d8xLEcqTghCE,10
18
- sqlengine_lite-2.2.2.dist-info/RECORD,,