database-wrapper 0.2.33__tar.gz → 0.2.38__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.
- {database_wrapper-0.2.33 → database_wrapper-0.2.38}/PKG-INFO +6 -6
- {database_wrapper-0.2.33 → database_wrapper-0.2.38}/database_wrapper/__init__.py +2 -1
- {database_wrapper-0.2.33 → database_wrapper-0.2.38}/database_wrapper/abc.py +6 -1
- database_wrapper-0.2.38/database_wrapper/common.py +27 -0
- {database_wrapper-0.2.33 → database_wrapper-0.2.38}/database_wrapper/config.py +3 -3
- {database_wrapper-0.2.33 → database_wrapper-0.2.38}/database_wrapper/db_backend.py +18 -8
- {database_wrapper-0.2.33 → database_wrapper-0.2.38}/database_wrapper/db_data_model.py +3 -0
- {database_wrapper-0.2.33 → database_wrapper-0.2.38}/database_wrapper/db_introspector.py +27 -18
- {database_wrapper-0.2.33 → database_wrapper-0.2.38}/database_wrapper/db_wrapper.py +15 -11
- {database_wrapper-0.2.33 → database_wrapper-0.2.38}/database_wrapper/db_wrapper_async.py +15 -11
- {database_wrapper-0.2.33 → database_wrapper-0.2.38}/database_wrapper/db_wrapper_mixin.py +95 -25
- {database_wrapper-0.2.33 → database_wrapper-0.2.38}/database_wrapper/serialization.py +17 -6
- {database_wrapper-0.2.33 → database_wrapper-0.2.38}/database_wrapper.egg-info/PKG-INFO +6 -6
- {database_wrapper-0.2.33 → database_wrapper-0.2.38}/database_wrapper.egg-info/requires.txt +5 -5
- {database_wrapper-0.2.33 → database_wrapper-0.2.38}/pyproject.toml +6 -6
- database_wrapper-0.2.33/database_wrapper/common.py +0 -14
- {database_wrapper-0.2.33 → database_wrapper-0.2.38}/README.md +0 -0
- {database_wrapper-0.2.33 → database_wrapper-0.2.38}/database_wrapper/py.typed +0 -0
- {database_wrapper-0.2.33 → database_wrapper-0.2.38}/database_wrapper/utils/__init__.py +0 -0
- {database_wrapper-0.2.33 → database_wrapper-0.2.38}/database_wrapper/utils/dataclass_addons.py +0 -0
- {database_wrapper-0.2.33 → database_wrapper-0.2.38}/database_wrapper.egg-info/SOURCES.txt +0 -0
- {database_wrapper-0.2.33 → database_wrapper-0.2.38}/database_wrapper.egg-info/dependency_links.txt +0 -0
- {database_wrapper-0.2.33 → database_wrapper-0.2.38}/database_wrapper.egg-info/top_level.txt +0 -0
- {database_wrapper-0.2.33 → database_wrapper-0.2.38}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: database_wrapper
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.38
|
|
4
4
|
Summary: A Different Approach to Database Wrappers in Python
|
|
5
5
|
Author-email: Gints Murans <gm@gm.lv>
|
|
6
6
|
License: GNU General Public License v3.0 (GPL-3.0)
|
|
@@ -33,15 +33,15 @@ Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
|
33
33
|
Requires-Python: >=3.8
|
|
34
34
|
Description-Content-Type: text/markdown
|
|
35
35
|
Provides-Extra: pgsql
|
|
36
|
-
Requires-Dist: database_wrapper_pgsql==0.2.
|
|
36
|
+
Requires-Dist: database_wrapper_pgsql==0.2.38; extra == "pgsql"
|
|
37
37
|
Provides-Extra: mysql
|
|
38
|
-
Requires-Dist: database_wrapper_mysql==0.2.
|
|
38
|
+
Requires-Dist: database_wrapper_mysql==0.2.38; extra == "mysql"
|
|
39
39
|
Provides-Extra: mssql
|
|
40
|
-
Requires-Dist: database_wrapper_mssql==0.2.
|
|
40
|
+
Requires-Dist: database_wrapper_mssql==0.2.38; extra == "mssql"
|
|
41
41
|
Provides-Extra: sqlite
|
|
42
|
-
Requires-Dist: database_wrapper_sqlite==0.2.
|
|
42
|
+
Requires-Dist: database_wrapper_sqlite==0.2.38; extra == "sqlite"
|
|
43
43
|
Provides-Extra: redis
|
|
44
|
-
Requires-Dist: database_wrapper_redis==0.2.
|
|
44
|
+
Requires-Dist: database_wrapper_redis==0.2.38; extra == "redis"
|
|
45
45
|
Provides-Extra: all
|
|
46
46
|
Requires-Dist: database_wrapper[mssql,mysql,pgsql,redis,sqlite]; extra == "all"
|
|
47
47
|
Provides-Extra: dev
|
|
@@ -8,7 +8,7 @@ import logging
|
|
|
8
8
|
|
|
9
9
|
from . import utils
|
|
10
10
|
from .abc import ConnectionABC, ConnectionAsyncABC, CursorABC, CursorAsyncABC
|
|
11
|
-
from .common import DataModelType, NoParam, OrderByItem
|
|
11
|
+
from .common import DataModelType, NoParam, OrderByItem, RawSQL
|
|
12
12
|
from .db_backend import DatabaseBackend
|
|
13
13
|
from .db_data_model import DBDataModel, DBDefaultsDataModel, MetadataDict
|
|
14
14
|
from .db_introspector import ColumnMetaIntrospector, DBIntrospector
|
|
@@ -38,6 +38,7 @@ __all__ = [
|
|
|
38
38
|
"DataModelType",
|
|
39
39
|
"OrderByItem",
|
|
40
40
|
"NoParam",
|
|
41
|
+
"RawSQL",
|
|
41
42
|
"utils",
|
|
42
43
|
"SerializeType",
|
|
43
44
|
"ignore_unknown_kwargs",
|
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
from collections.abc import Sequence
|
|
2
2
|
from typing import Any, Literal, Protocol
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
try:
|
|
5
|
+
# Only used in type hints; psycopg is a dependency of the pgsql adapter,
|
|
6
|
+
# not of the core package
|
|
7
|
+
from psycopg.sql import Composable
|
|
8
|
+
except ImportError:
|
|
9
|
+
Composable = Any # type: ignore[assignment,misc]
|
|
5
10
|
|
|
6
11
|
Row = dict[str, Any]
|
|
7
12
|
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
from typing import TypeVar
|
|
2
|
+
|
|
3
|
+
from .db_data_model import DBDataModel
|
|
4
|
+
|
|
5
|
+
# Bound T to DBDataModel
|
|
6
|
+
DataModelType = TypeVar("DataModelType", bound=DBDataModel)
|
|
7
|
+
|
|
8
|
+
# OrderByItem type
|
|
9
|
+
OrderByItem = list[tuple[str, str | None]]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
# NoParam class
|
|
13
|
+
class NoParam:
|
|
14
|
+
pass
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class RawSQL(str):
|
|
18
|
+
"""
|
|
19
|
+
Marks a filter/order-by key as a raw SQL expression, skipping identifier
|
|
20
|
+
validation. Only use with trusted, developer-controlled strings - the
|
|
21
|
+
value is interpolated into the query verbatim.
|
|
22
|
+
|
|
23
|
+
Example:
|
|
24
|
+
wrapper.get_filtered(model, {RawSQL("LOWER(name)"): "alice"})
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
__slots__ = ()
|
|
@@ -3,7 +3,7 @@ from typing import Any
|
|
|
3
3
|
CONFIG: dict[str, Any] = {
|
|
4
4
|
# These are supposed to be set automatically by a git pre-compile script
|
|
5
5
|
# They are one git commit hash behind, if used automatically
|
|
6
|
-
"git_commit_hash": "
|
|
7
|
-
"git_commit_date": "
|
|
8
|
-
"app_version": "0.2.
|
|
6
|
+
"git_commit_hash": "e7b8fcc2e923824a5ebbf1f959b3f8872c9e6849",
|
|
7
|
+
"git_commit_date": "04.07.2026 14:45",
|
|
8
|
+
"app_version": "0.2.38",
|
|
9
9
|
}
|
|
@@ -97,18 +97,28 @@ class DatabaseBackend:
|
|
|
97
97
|
|
|
98
98
|
def __del__(self) -> None:
|
|
99
99
|
"""What to do when class is destroyed"""
|
|
100
|
-
self
|
|
100
|
+
if hasattr(self, "logger"):
|
|
101
|
+
self.logger.debug("Dealloc")
|
|
101
102
|
|
|
102
|
-
# Clean up connections
|
|
103
|
-
|
|
104
|
-
self
|
|
103
|
+
# Clean up connections; a partially initialized instance
|
|
104
|
+
# (failed __init__) may not have these attributes yet
|
|
105
|
+
if hasattr(self, "connection"):
|
|
106
|
+
self.close()
|
|
107
|
+
if hasattr(self, "pool") or hasattr(self, "pool_async"):
|
|
108
|
+
self.close_pool()
|
|
105
109
|
|
|
106
110
|
# Clean just in case
|
|
107
|
-
|
|
108
|
-
|
|
111
|
+
if hasattr(self, "connection"):
|
|
112
|
+
del self.connection
|
|
109
113
|
|
|
110
|
-
|
|
111
|
-
|
|
114
|
+
if hasattr(self, "cursor"):
|
|
115
|
+
del self.cursor
|
|
116
|
+
|
|
117
|
+
if hasattr(self, "pool"):
|
|
118
|
+
del self.pool
|
|
119
|
+
|
|
120
|
+
if hasattr(self, "pool_async"):
|
|
121
|
+
del self.pool_async
|
|
112
122
|
|
|
113
123
|
###############
|
|
114
124
|
### Context ###
|
|
@@ -161,6 +161,9 @@ class DBDataModel:
|
|
|
161
161
|
for field_name, value in pairs:
|
|
162
162
|
class_field = self.__dataclass_fields__.get(field_name, None)
|
|
163
163
|
if class_field is None:
|
|
164
|
+
# asdict() also calls this factory for nested dataclasses whose
|
|
165
|
+
# fields are not on this model - pass them through unfiltered
|
|
166
|
+
new_dict[field_name] = value
|
|
164
167
|
continue
|
|
165
168
|
|
|
166
169
|
metadata = cast(MetadataDict, class_field.metadata)
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import re
|
|
2
|
+
import types
|
|
1
3
|
from dataclasses import MISSING, dataclass, field, make_dataclass
|
|
2
4
|
from dataclasses import fields as dc_fields
|
|
3
5
|
from datetime import date, datetime
|
|
@@ -12,7 +14,8 @@ from .serialization import SerializeType
|
|
|
12
14
|
def type_to_str(t: Any) -> str:
|
|
13
15
|
"""Render annotations like 'str | None' or 'RV4ProductionJobStatus | None'."""
|
|
14
16
|
origin = get_origin(t)
|
|
15
|
-
|
|
17
|
+
# typing.Union and the `X | Y` UnionType are distinct origins before Python 3.14
|
|
18
|
+
if origin is Union or origin is types.UnionType:
|
|
16
19
|
args = list(get_args(t))
|
|
17
20
|
# Optional[T] -> Union[T, NoneType]
|
|
18
21
|
if type(None) in args and len(args) == 2:
|
|
@@ -31,12 +34,17 @@ def _make_enum(name: str, labels: list[str]) -> Enum:
|
|
|
31
34
|
# Normalize labels to valid identifiers
|
|
32
35
|
members = {}
|
|
33
36
|
for raw in labels:
|
|
34
|
-
key =
|
|
37
|
+
key = re.sub(r"\W", "_", raw.upper())
|
|
35
38
|
# avoid starting with digit
|
|
36
|
-
if key
|
|
39
|
+
if not key or key[0].isdigit():
|
|
37
40
|
key = f"_{key}"
|
|
41
|
+
# avoid collisions after normalization (e.g. "a b" and "a_b")
|
|
42
|
+
if key in members:
|
|
43
|
+
key = f"{key}_{len(members)}"
|
|
38
44
|
members[key] = raw
|
|
39
|
-
|
|
45
|
+
# module="enum" marks this as dynamically created so render_dataclass_source
|
|
46
|
+
# embeds it in the generated file instead of emitting a bogus import
|
|
47
|
+
return Enum(name, members, module="enum")
|
|
40
48
|
|
|
41
49
|
|
|
42
50
|
@dataclass(frozen=True)
|
|
@@ -128,10 +136,7 @@ class DBIntrospector:
|
|
|
128
136
|
py_type, serialize = self.map_db_type(c.db_type)
|
|
129
137
|
|
|
130
138
|
# Optional typing if nullable
|
|
131
|
-
if c.is_nullable
|
|
132
|
-
ann: type[py_type] | None = py_type
|
|
133
|
-
else:
|
|
134
|
-
ann = py_type
|
|
139
|
+
ann: Any = py_type | None if c.is_nullable else py_type
|
|
135
140
|
|
|
136
141
|
# Default value choice
|
|
137
142
|
default = None
|
|
@@ -144,7 +149,7 @@ class DBIntrospector:
|
|
|
144
149
|
default = py_type() # 0, 0.0, ""
|
|
145
150
|
elif py_type is datetime:
|
|
146
151
|
default_factory = datetime.now
|
|
147
|
-
elif py_type is
|
|
152
|
+
elif py_type is date:
|
|
148
153
|
default_factory = date.today
|
|
149
154
|
elif enum_class:
|
|
150
155
|
# pick first enum value as default
|
|
@@ -185,7 +190,7 @@ class DBIntrospector:
|
|
|
185
190
|
)
|
|
186
191
|
)
|
|
187
192
|
|
|
188
|
-
# Build class with properties
|
|
193
|
+
# Build class with properties schema_name/table_name
|
|
189
194
|
# We’ll generate methods dynamically and attach.
|
|
190
195
|
cls = make_dataclass(
|
|
191
196
|
class_name,
|
|
@@ -197,15 +202,16 @@ class DBIntrospector:
|
|
|
197
202
|
repr=True,
|
|
198
203
|
)
|
|
199
204
|
|
|
200
|
-
# Attach
|
|
201
|
-
|
|
205
|
+
# Attach schema_name/table_name as properties - these are what
|
|
206
|
+
# DBWrapper reads when building queries
|
|
207
|
+
def _schema_name(self) -> str:
|
|
202
208
|
return schema
|
|
203
209
|
|
|
204
|
-
def
|
|
210
|
+
def _table_name(self) -> str:
|
|
205
211
|
return table
|
|
206
212
|
|
|
207
|
-
cls.
|
|
208
|
-
cls.
|
|
213
|
+
cls.schema_name = property(_schema_name)
|
|
214
|
+
cls.table_name = property(_table_name)
|
|
209
215
|
|
|
210
216
|
return cls
|
|
211
217
|
|
|
@@ -260,7 +266,7 @@ class DBIntrospector:
|
|
|
260
266
|
lines: list[str] = []
|
|
261
267
|
# Imports
|
|
262
268
|
lines.append("from typing import Any, Optional")
|
|
263
|
-
lines.append("from datetime import datetime")
|
|
269
|
+
lines.append("from datetime import date, datetime, time")
|
|
264
270
|
lines.append("from dataclasses import dataclass, field")
|
|
265
271
|
lines.append("")
|
|
266
272
|
lines.append("from database_wrapper import MetadataDict, DBDefaultsDataModel, SerializeType")
|
|
@@ -290,11 +296,11 @@ class DBIntrospector:
|
|
|
290
296
|
lines.append(' """Auto-generated from database schema"""')
|
|
291
297
|
lines.append("")
|
|
292
298
|
lines.append(" @property")
|
|
293
|
-
lines.append(" def
|
|
299
|
+
lines.append(" def schema_name(self) -> str:")
|
|
294
300
|
lines.append(f" return {schema!r}")
|
|
295
301
|
lines.append("")
|
|
296
302
|
lines.append(" @property")
|
|
297
|
-
lines.append(" def
|
|
303
|
+
lines.append(" def table_name(self) -> str:")
|
|
298
304
|
lines.append(f" return {table!r}")
|
|
299
305
|
lines.append("")
|
|
300
306
|
|
|
@@ -360,6 +366,9 @@ class DBIntrospector:
|
|
|
360
366
|
lines.append(" # Explicitly list each field (stable order)")
|
|
361
367
|
for f in dc_fields(cls):
|
|
362
368
|
md: MetadataDict = dict(f.metadata) if f.metadata else {}
|
|
369
|
+
if md.get("exclude", False):
|
|
370
|
+
continue
|
|
371
|
+
|
|
363
372
|
serialize = md.get("serialize")
|
|
364
373
|
key = f.name
|
|
365
374
|
if serialize == SerializeType.DATETIME:
|
|
@@ -36,7 +36,7 @@ class DBWrapper(DBWrapperMixin):
|
|
|
36
36
|
id_value = empty_data_class.id_value
|
|
37
37
|
if not id_key:
|
|
38
38
|
raise ValueError("Id key is not set")
|
|
39
|
-
if
|
|
39
|
+
if id_value is None:
|
|
40
40
|
raise ValueError("Id value is not set")
|
|
41
41
|
|
|
42
42
|
# Get the record
|
|
@@ -122,7 +122,7 @@ class DBWrapper(DBWrapperMixin):
|
|
|
122
122
|
_filter = None
|
|
123
123
|
|
|
124
124
|
# TODO: Rewrite this so that filter method with loop is not used here
|
|
125
|
-
if id_key and id_value:
|
|
125
|
+
if id_key and id_value is not None:
|
|
126
126
|
(_filter, _params) = self.create_filter({id_key: id_value})
|
|
127
127
|
|
|
128
128
|
# Order and limit
|
|
@@ -223,12 +223,14 @@ class DBWrapper(DBWrapperMixin):
|
|
|
223
223
|
# Insert
|
|
224
224
|
self.db_cursor.execute(insert_query, tuple(values))
|
|
225
225
|
affected_rows = self.db_cursor.rowcount
|
|
226
|
-
result = self.db_cursor.fetchone()
|
|
227
226
|
|
|
228
|
-
|
|
229
|
-
result
|
|
230
|
-
|
|
231
|
-
|
|
227
|
+
if self.insert_returning:
|
|
228
|
+
result = self.db_cursor.fetchone()
|
|
229
|
+
new_id = result[id_key] if result and id_key in result else 0
|
|
230
|
+
else:
|
|
231
|
+
new_id = self.db_cursor.lastrowid or 0
|
|
232
|
+
|
|
233
|
+
return (new_id, affected_rows)
|
|
232
234
|
|
|
233
235
|
@overload
|
|
234
236
|
def insert(self, records: DataModelType) -> tuple[int, int]: ...
|
|
@@ -362,7 +364,7 @@ class DBWrapper(DBWrapperMixin):
|
|
|
362
364
|
update_data = row.update_data()
|
|
363
365
|
update_id_key = row.id_key
|
|
364
366
|
update_id_value = row.id_value
|
|
365
|
-
if not update_data or not update_id_key or
|
|
367
|
+
if not update_data or not update_id_key or update_id_value is None:
|
|
366
368
|
continue
|
|
367
369
|
|
|
368
370
|
status.append(
|
|
@@ -390,8 +392,10 @@ class DBWrapper(DBWrapperMixin):
|
|
|
390
392
|
update_id_key: str | None = None,
|
|
391
393
|
update_id_value: Any = None,
|
|
392
394
|
) -> int:
|
|
393
|
-
|
|
394
|
-
|
|
395
|
+
if update_id_key is None:
|
|
396
|
+
update_id_key = record.id_key
|
|
397
|
+
if update_id_value is None:
|
|
398
|
+
update_id_value = record.id_value
|
|
395
399
|
status = self._update(
|
|
396
400
|
record,
|
|
397
401
|
record.schema_name,
|
|
@@ -466,7 +470,7 @@ class DBWrapper(DBWrapperMixin):
|
|
|
466
470
|
for row in records:
|
|
467
471
|
delete_id_key = row.id_key
|
|
468
472
|
delete_id_value = row.id_value
|
|
469
|
-
if not delete_id_key or
|
|
473
|
+
if not delete_id_key or delete_id_value is None:
|
|
470
474
|
continue
|
|
471
475
|
|
|
472
476
|
status.append(
|
|
@@ -38,7 +38,7 @@ class DBWrapperAsync(DBWrapperMixin):
|
|
|
38
38
|
id_value = empty_data_class.id_value
|
|
39
39
|
if not id_key:
|
|
40
40
|
raise ValueError("Id key is not set")
|
|
41
|
-
if
|
|
41
|
+
if id_value is None:
|
|
42
42
|
raise ValueError("Id value is not set")
|
|
43
43
|
|
|
44
44
|
# Get the record
|
|
@@ -124,7 +124,7 @@ class DBWrapperAsync(DBWrapperMixin):
|
|
|
124
124
|
_filter = None
|
|
125
125
|
|
|
126
126
|
# TODO: Rewrite this so that filter method with loop is not used here
|
|
127
|
-
if id_key and id_value:
|
|
127
|
+
if id_key and id_value is not None:
|
|
128
128
|
(_filter, _params) = self.create_filter({id_key: id_value})
|
|
129
129
|
|
|
130
130
|
# Order and limit
|
|
@@ -225,12 +225,14 @@ class DBWrapperAsync(DBWrapperMixin):
|
|
|
225
225
|
# Insert
|
|
226
226
|
await self.db_cursor.execute(insert_query, tuple(values))
|
|
227
227
|
affected_rows = self.db_cursor.rowcount
|
|
228
|
-
result = await self.db_cursor.fetchone()
|
|
229
228
|
|
|
230
|
-
|
|
231
|
-
result
|
|
232
|
-
|
|
233
|
-
|
|
229
|
+
if self.insert_returning:
|
|
230
|
+
result = await self.db_cursor.fetchone()
|
|
231
|
+
new_id = result[id_key] if result and id_key in result else 0
|
|
232
|
+
else:
|
|
233
|
+
new_id = self.db_cursor.lastrowid or 0
|
|
234
|
+
|
|
235
|
+
return (new_id, affected_rows)
|
|
234
236
|
|
|
235
237
|
@overload
|
|
236
238
|
async def insert(self, records: DataModelType) -> tuple[int, int]: ...
|
|
@@ -363,7 +365,7 @@ class DBWrapperAsync(DBWrapperMixin):
|
|
|
363
365
|
update_data = row.update_data()
|
|
364
366
|
update_id_key = row.id_key
|
|
365
367
|
update_id_value = row.id_value
|
|
366
|
-
if not update_data or not update_id_key or
|
|
368
|
+
if not update_data or not update_id_key or update_id_value is None:
|
|
367
369
|
continue
|
|
368
370
|
|
|
369
371
|
status.append(
|
|
@@ -391,8 +393,10 @@ class DBWrapperAsync(DBWrapperMixin):
|
|
|
391
393
|
update_id_key: str | None = None,
|
|
392
394
|
update_id_value: Any = None,
|
|
393
395
|
) -> int:
|
|
394
|
-
|
|
395
|
-
|
|
396
|
+
if update_id_key is None:
|
|
397
|
+
update_id_key = record.id_key
|
|
398
|
+
if update_id_value is None:
|
|
399
|
+
update_id_value = record.id_value
|
|
396
400
|
status = await self._update(
|
|
397
401
|
record,
|
|
398
402
|
record.schema_name,
|
|
@@ -467,7 +471,7 @@ class DBWrapperAsync(DBWrapperMixin):
|
|
|
467
471
|
for row in records:
|
|
468
472
|
delete_id_key = row.id_key
|
|
469
473
|
delete_id_value = row.id_value
|
|
470
|
-
if not delete_id_key or
|
|
474
|
+
if not delete_id_key or delete_id_value is None:
|
|
471
475
|
continue
|
|
472
476
|
|
|
473
477
|
status.append(
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import logging
|
|
2
|
+
import re
|
|
2
3
|
from typing import Any, cast
|
|
3
4
|
|
|
4
|
-
from .common import DataModelType, NoParam, OrderByItem
|
|
5
|
+
from .common import DataModelType, NoParam, OrderByItem, RawSQL
|
|
6
|
+
|
|
7
|
+
# Plain identifiers, optionally dot-qualified (schema.table, alias.column)
|
|
8
|
+
IDENTIFIER_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$")
|
|
5
9
|
|
|
6
10
|
|
|
7
11
|
class DBWrapperMixin:
|
|
@@ -26,6 +30,12 @@ class DBWrapperMixin:
|
|
|
26
30
|
logger: Any
|
|
27
31
|
"""Logger object"""
|
|
28
32
|
|
|
33
|
+
placeholder: str = "%s"
|
|
34
|
+
"""Parameter placeholder used by the underlying driver (paramstyle)."""
|
|
35
|
+
|
|
36
|
+
insert_returning: bool = True
|
|
37
|
+
"""Whether INSERT supports a RETURNING clause to fetch the new id."""
|
|
38
|
+
|
|
29
39
|
#######################
|
|
30
40
|
### Class lifecycle ###
|
|
31
41
|
#######################
|
|
@@ -55,7 +65,8 @@ class DBWrapperMixin:
|
|
|
55
65
|
"""
|
|
56
66
|
Deallocates the instance of the DBWrapper class.
|
|
57
67
|
"""
|
|
58
|
-
self
|
|
68
|
+
if hasattr(self, "logger"):
|
|
69
|
+
self.logger.debug("Dealloc")
|
|
59
70
|
|
|
60
71
|
# Force remove instances so that there are no circular references
|
|
61
72
|
if hasattr(self, "db_cursor") and self.db_cursor:
|
|
@@ -74,7 +85,8 @@ class DBWrapperMixin:
|
|
|
74
85
|
"""
|
|
75
86
|
|
|
76
87
|
if db_cursor is None:
|
|
77
|
-
|
|
88
|
+
if hasattr(self, "db_cursor"):
|
|
89
|
+
del self.db_cursor
|
|
78
90
|
return
|
|
79
91
|
|
|
80
92
|
self.db_cursor = db_cursor
|
|
@@ -83,6 +95,30 @@ class DBWrapperMixin:
|
|
|
83
95
|
### Helper methods ###
|
|
84
96
|
######################
|
|
85
97
|
|
|
98
|
+
def validate_identifier(self, name: str) -> str:
|
|
99
|
+
"""
|
|
100
|
+
Validates that the given name is a safe SQL identifier.
|
|
101
|
+
|
|
102
|
+
Identifiers (table names, column names, filter and order-by keys) are
|
|
103
|
+
interpolated into queries directly, so anything beyond plain
|
|
104
|
+
(optionally dot-qualified) identifiers is rejected to prevent SQL injection.
|
|
105
|
+
|
|
106
|
+
Wrap trusted expressions in RawSQL to bypass validation deliberately.
|
|
107
|
+
|
|
108
|
+
Args:
|
|
109
|
+
name (str): The identifier to validate.
|
|
110
|
+
|
|
111
|
+
Returns:
|
|
112
|
+
str: The validated identifier.
|
|
113
|
+
"""
|
|
114
|
+
if isinstance(name, RawSQL):
|
|
115
|
+
return name
|
|
116
|
+
|
|
117
|
+
if not isinstance(name, str) or not IDENTIFIER_PATTERN.match(name):
|
|
118
|
+
raise ValueError(f"Invalid SQL identifier: {name!r}")
|
|
119
|
+
|
|
120
|
+
return name
|
|
121
|
+
|
|
86
122
|
def make_identifier(self, schema: str | None, name: str) -> Any:
|
|
87
123
|
"""
|
|
88
124
|
Creates a SQL identifier object from the given name.
|
|
@@ -94,7 +130,9 @@ class DBWrapperMixin:
|
|
|
94
130
|
Returns:
|
|
95
131
|
str: The created SQL identifier object.
|
|
96
132
|
"""
|
|
133
|
+
self.validate_identifier(name)
|
|
97
134
|
if schema:
|
|
135
|
+
self.validate_identifier(schema)
|
|
98
136
|
return f"{schema}.{name}"
|
|
99
137
|
|
|
100
138
|
return name
|
|
@@ -169,9 +207,28 @@ class DBWrapperMixin:
|
|
|
169
207
|
if order_by is None:
|
|
170
208
|
return None
|
|
171
209
|
|
|
172
|
-
order_list = [f"{item[0]} {
|
|
210
|
+
order_list = [f"{self.validate_identifier(item[0])} {self.order_direction(item)}" for item in order_by]
|
|
173
211
|
return "ORDER BY {}".format(", ".join(order_list))
|
|
174
212
|
|
|
213
|
+
def order_direction(self, item: tuple[str, str | None] | tuple[str]) -> str:
|
|
214
|
+
"""
|
|
215
|
+
Extracts and validates the sort direction from an order-by item.
|
|
216
|
+
|
|
217
|
+
Args:
|
|
218
|
+
item (tuple): The order-by item (column, direction).
|
|
219
|
+
|
|
220
|
+
Returns:
|
|
221
|
+
str: "ASC" or "DESC".
|
|
222
|
+
"""
|
|
223
|
+
if len(item) < 2 or item[1] is None:
|
|
224
|
+
return "ASC"
|
|
225
|
+
|
|
226
|
+
direction = str(item[1]).upper()
|
|
227
|
+
if direction not in ("ASC", "DESC"):
|
|
228
|
+
raise ValueError(f"Invalid sort direction: {item[1]!r}")
|
|
229
|
+
|
|
230
|
+
return direction
|
|
231
|
+
|
|
175
232
|
def limit_query(self, offset: int = 0, limit: int = 100) -> Any | None:
|
|
176
233
|
"""
|
|
177
234
|
Creates a SQL query to limit the number of results returned.
|
|
@@ -186,42 +243,51 @@ class DBWrapperMixin:
|
|
|
186
243
|
if limit == 0:
|
|
187
244
|
return None
|
|
188
245
|
|
|
189
|
-
return f"LIMIT {limit} OFFSET {offset}"
|
|
246
|
+
return f"LIMIT {int(limit)} OFFSET {int(offset)}"
|
|
190
247
|
|
|
191
248
|
def format_filter(self, key: str, filter: Any) -> tuple[Any, ...]:
|
|
249
|
+
self.validate_identifier(key)
|
|
250
|
+
ph = self.placeholder
|
|
251
|
+
|
|
192
252
|
if type(filter) is dict:
|
|
193
253
|
if "$contains" in filter:
|
|
194
254
|
return (
|
|
195
|
-
f"{key} LIKE
|
|
255
|
+
f"{key} LIKE {ph}",
|
|
196
256
|
f"%{filter['$contains']}%",
|
|
197
257
|
)
|
|
198
258
|
elif "$starts_with" in filter:
|
|
199
|
-
return (f"{key} LIKE
|
|
259
|
+
return (f"{key} LIKE {ph}", f"{filter['$starts_with']}%")
|
|
200
260
|
elif "$ends_with" in filter:
|
|
201
|
-
return (f"{key} LIKE
|
|
261
|
+
return (f"{key} LIKE {ph}", f"%{filter['$ends_with']}")
|
|
202
262
|
elif "$min" in filter and "$max" not in filter:
|
|
203
|
-
return (f"{key} >=
|
|
263
|
+
return (f"{key} >= {ph}", filter["$min"])
|
|
204
264
|
elif "$max" in filter and "$min" not in filter:
|
|
205
|
-
return (f"{key} <=
|
|
265
|
+
return (f"{key} <= {ph}", filter["$max"])
|
|
206
266
|
elif "$min" in filter and "$max" in filter:
|
|
207
|
-
return (f"{key} BETWEEN
|
|
267
|
+
return (f"{key} BETWEEN {ph} AND {ph}", filter["$min"], filter["$max"])
|
|
208
268
|
elif "$in" in filter:
|
|
209
269
|
in_filter_1: list[Any] = cast(list[Any], filter["$in"])
|
|
210
|
-
|
|
270
|
+
if not in_filter_1:
|
|
271
|
+
# Empty IN list matches nothing
|
|
272
|
+
return ("1 = 0",)
|
|
273
|
+
return (f"{key} IN ({', '.join([ph] * len(in_filter_1))})",) + tuple(in_filter_1)
|
|
211
274
|
elif "$not_in" in filter:
|
|
212
275
|
in_filter_2: list[Any] = cast(list[Any], filter["$not_in"])
|
|
213
|
-
|
|
276
|
+
if not in_filter_2:
|
|
277
|
+
# Empty NOT IN list matches everything
|
|
278
|
+
return ("1 = 1",)
|
|
279
|
+
return (f"{key} NOT IN ({', '.join([ph] * len(in_filter_2))})",) + tuple(in_filter_2)
|
|
214
280
|
elif "$not" in filter:
|
|
215
|
-
return (f"{key} !=
|
|
281
|
+
return (f"{key} != {ph}", filter["$not"])
|
|
216
282
|
|
|
217
283
|
elif "$gt" in filter:
|
|
218
|
-
return (f"{key} >
|
|
284
|
+
return (f"{key} > {ph}", filter["$gt"])
|
|
219
285
|
elif "$gte" in filter:
|
|
220
|
-
return (f"{key} >=
|
|
286
|
+
return (f"{key} >= {ph}", filter["$gte"])
|
|
221
287
|
elif "$lt" in filter:
|
|
222
|
-
return (f"{key} <
|
|
288
|
+
return (f"{key} < {ph}", filter["$lt"])
|
|
223
289
|
elif "$lte" in filter:
|
|
224
|
-
return (f"{key} <=
|
|
290
|
+
return (f"{key} <= {ph}", filter["$lte"])
|
|
225
291
|
elif "$is_null" in filter:
|
|
226
292
|
return (f"{key} IS NULL",)
|
|
227
293
|
elif "$is_not_null" in filter:
|
|
@@ -229,7 +295,7 @@ class DBWrapperMixin:
|
|
|
229
295
|
|
|
230
296
|
raise NotImplementedError("Filter type not supported")
|
|
231
297
|
elif isinstance(filter, (bool, str, int, float)):
|
|
232
|
-
return (f"{key} =
|
|
298
|
+
return (f"{key} = {ph}", filter)
|
|
233
299
|
else:
|
|
234
300
|
raise NotImplementedError(f"Filter type not supported: {key} = {type(filter)}")
|
|
235
301
|
|
|
@@ -268,9 +334,13 @@ class DBWrapperMixin:
|
|
|
268
334
|
keys = store_data.keys()
|
|
269
335
|
values = list(store_data.values())
|
|
270
336
|
|
|
271
|
-
columns = ", ".join(keys)
|
|
272
|
-
values_placeholder = ", ".join([
|
|
273
|
-
|
|
337
|
+
columns = ", ".join(self.validate_identifier(key) for key in keys)
|
|
338
|
+
values_placeholder = ", ".join([self.placeholder] * len(values))
|
|
339
|
+
query = f"INSERT INTO {table_identifier} ({columns}) VALUES ({values_placeholder})"
|
|
340
|
+
if self.insert_returning:
|
|
341
|
+
query += f" RETURNING {return_key}"
|
|
342
|
+
|
|
343
|
+
return query
|
|
274
344
|
|
|
275
345
|
def _format_update_query(
|
|
276
346
|
self,
|
|
@@ -279,12 +349,12 @@ class DBWrapperMixin:
|
|
|
279
349
|
update_data: dict[str, Any],
|
|
280
350
|
) -> Any:
|
|
281
351
|
keys = update_data.keys()
|
|
282
|
-
set_clause = ", ".join(f"{key} =
|
|
283
|
-
return f"UPDATE {table_identifier} SET {set_clause} WHERE {update_key} =
|
|
352
|
+
set_clause = ", ".join(f"{self.validate_identifier(key)} = {self.placeholder}" for key in keys)
|
|
353
|
+
return f"UPDATE {table_identifier} SET {set_clause} WHERE {update_key} = {self.placeholder}"
|
|
284
354
|
|
|
285
355
|
def _format_delete_query(
|
|
286
356
|
self,
|
|
287
357
|
table_identifier: Any,
|
|
288
358
|
delete_key: Any,
|
|
289
359
|
) -> Any:
|
|
290
|
-
return f"DELETE FROM {table_identifier} WHERE {delete_key} =
|
|
360
|
+
return f"DELETE FROM {table_identifier} WHERE {delete_key} = {self.placeholder}"
|
|
@@ -18,8 +18,10 @@ def json_encoder(obj: Any) -> Any:
|
|
|
18
18
|
if isinstance(obj, Decimal):
|
|
19
19
|
return float(obj)
|
|
20
20
|
|
|
21
|
-
|
|
22
|
-
|
|
21
|
+
# isoformat preserves timezone offset and sub-second precision;
|
|
22
|
+
# plain dates render as date-only strings
|
|
23
|
+
if isinstance(obj, (datetime.datetime, datetime.date)):
|
|
24
|
+
return obj.isoformat()
|
|
23
25
|
|
|
24
26
|
if isinstance(obj, Enum):
|
|
25
27
|
return obj.value
|
|
@@ -31,6 +33,11 @@ def json_encoder(obj: Any) -> Any:
|
|
|
31
33
|
|
|
32
34
|
|
|
33
35
|
def serialize_value(value: Any, s_type: SerializeType) -> Any:
|
|
36
|
+
# None always serializes to SQL NULL - otherwise nullable enum fields crash
|
|
37
|
+
# on .value and JSON fields store the string 'null' instead of NULL
|
|
38
|
+
if value is None:
|
|
39
|
+
return None
|
|
40
|
+
|
|
34
41
|
if s_type == SerializeType.DATETIME:
|
|
35
42
|
if not isinstance(value, datetime.datetime):
|
|
36
43
|
return value
|
|
@@ -64,6 +71,9 @@ def deserialize_value(
|
|
|
64
71
|
timezone: str | datetime.tzinfo | None = None,
|
|
65
72
|
) -> Any:
|
|
66
73
|
if s_type == SerializeType.DATETIME:
|
|
74
|
+
if timezone is not None and isinstance(timezone, str):
|
|
75
|
+
timezone = ZoneInfo(timezone)
|
|
76
|
+
|
|
67
77
|
if isinstance(value, datetime.datetime):
|
|
68
78
|
return value
|
|
69
79
|
|
|
@@ -73,12 +83,13 @@ def deserialize_value(
|
|
|
73
83
|
if timestamp > 1e10: # Check if timestamp is in milliseconds
|
|
74
84
|
timestamp /= 1000
|
|
75
85
|
|
|
76
|
-
if timezone is not None and isinstance(timezone, str):
|
|
77
|
-
timezone = ZoneInfo(timezone)
|
|
78
|
-
|
|
79
86
|
return datetime.datetime.fromtimestamp(timestamp, tz=timezone)
|
|
80
87
|
|
|
81
|
-
|
|
88
|
+
parsed = datetime.datetime.fromisoformat(value)
|
|
89
|
+
if timezone is not None and parsed.tzinfo is None:
|
|
90
|
+
parsed = parsed.replace(tzinfo=timezone)
|
|
91
|
+
|
|
92
|
+
return parsed
|
|
82
93
|
|
|
83
94
|
if s_type == SerializeType.DATE:
|
|
84
95
|
if isinstance(value, datetime.date):
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: database_wrapper
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.38
|
|
4
4
|
Summary: A Different Approach to Database Wrappers in Python
|
|
5
5
|
Author-email: Gints Murans <gm@gm.lv>
|
|
6
6
|
License: GNU General Public License v3.0 (GPL-3.0)
|
|
@@ -33,15 +33,15 @@ Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
|
33
33
|
Requires-Python: >=3.8
|
|
34
34
|
Description-Content-Type: text/markdown
|
|
35
35
|
Provides-Extra: pgsql
|
|
36
|
-
Requires-Dist: database_wrapper_pgsql==0.2.
|
|
36
|
+
Requires-Dist: database_wrapper_pgsql==0.2.38; extra == "pgsql"
|
|
37
37
|
Provides-Extra: mysql
|
|
38
|
-
Requires-Dist: database_wrapper_mysql==0.2.
|
|
38
|
+
Requires-Dist: database_wrapper_mysql==0.2.38; extra == "mysql"
|
|
39
39
|
Provides-Extra: mssql
|
|
40
|
-
Requires-Dist: database_wrapper_mssql==0.2.
|
|
40
|
+
Requires-Dist: database_wrapper_mssql==0.2.38; extra == "mssql"
|
|
41
41
|
Provides-Extra: sqlite
|
|
42
|
-
Requires-Dist: database_wrapper_sqlite==0.2.
|
|
42
|
+
Requires-Dist: database_wrapper_sqlite==0.2.38; extra == "sqlite"
|
|
43
43
|
Provides-Extra: redis
|
|
44
|
-
Requires-Dist: database_wrapper_redis==0.2.
|
|
44
|
+
Requires-Dist: database_wrapper_redis==0.2.38; extra == "redis"
|
|
45
45
|
Provides-Extra: all
|
|
46
46
|
Requires-Dist: database_wrapper[mssql,mysql,pgsql,redis,sqlite]; extra == "all"
|
|
47
47
|
Provides-Extra: dev
|
|
@@ -17,16 +17,16 @@ mysqlclient>=2.2.2
|
|
|
17
17
|
pymssql>=2.2.10
|
|
18
18
|
|
|
19
19
|
[mssql]
|
|
20
|
-
database_wrapper_mssql==0.2.
|
|
20
|
+
database_wrapper_mssql==0.2.38
|
|
21
21
|
|
|
22
22
|
[mysql]
|
|
23
|
-
database_wrapper_mysql==0.2.
|
|
23
|
+
database_wrapper_mysql==0.2.38
|
|
24
24
|
|
|
25
25
|
[pgsql]
|
|
26
|
-
database_wrapper_pgsql==0.2.
|
|
26
|
+
database_wrapper_pgsql==0.2.38
|
|
27
27
|
|
|
28
28
|
[redis]
|
|
29
|
-
database_wrapper_redis==0.2.
|
|
29
|
+
database_wrapper_redis==0.2.38
|
|
30
30
|
|
|
31
31
|
[sqlite]
|
|
32
|
-
database_wrapper_sqlite==0.2.
|
|
32
|
+
database_wrapper_sqlite==0.2.38
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "database_wrapper"
|
|
7
|
-
version = "0.2.
|
|
7
|
+
version = "0.2.38"
|
|
8
8
|
description = "A Different Approach to Database Wrappers in Python"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.8"
|
|
@@ -52,11 +52,11 @@ Code = "https://github.com/gintsmurans/py_database_wrapper"
|
|
|
52
52
|
Download = "https://pypi.org/project/database_wrapper/"
|
|
53
53
|
|
|
54
54
|
[project.optional-dependencies]
|
|
55
|
-
pgsql = ["database_wrapper_pgsql == 0.2.
|
|
56
|
-
mysql = ["database_wrapper_mysql == 0.2.
|
|
57
|
-
mssql = ["database_wrapper_mssql == 0.2.
|
|
58
|
-
sqlite = ["database_wrapper_sqlite == 0.2.
|
|
59
|
-
redis = ["database_wrapper_redis == 0.2.
|
|
55
|
+
pgsql = ["database_wrapper_pgsql == 0.2.38"]
|
|
56
|
+
mysql = ["database_wrapper_mysql == 0.2.38"]
|
|
57
|
+
mssql = ["database_wrapper_mssql == 0.2.38"]
|
|
58
|
+
sqlite = ["database_wrapper_sqlite == 0.2.38"]
|
|
59
|
+
redis = ["database_wrapper_redis == 0.2.38"]
|
|
60
60
|
all = ["database_wrapper[pgsql,mysql,mssql,sqlite,redis]"]
|
|
61
61
|
dev = [
|
|
62
62
|
# Development
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
from typing import TypeVar
|
|
2
|
-
|
|
3
|
-
from .db_data_model import DBDataModel
|
|
4
|
-
|
|
5
|
-
# Bound T to DBDataModel
|
|
6
|
-
DataModelType = TypeVar("DataModelType", bound=DBDataModel)
|
|
7
|
-
|
|
8
|
-
# OrderByItem type
|
|
9
|
-
OrderByItem = list[tuple[str, str | None]]
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
# NoParam class
|
|
13
|
-
class NoParam:
|
|
14
|
-
pass
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{database_wrapper-0.2.33 → database_wrapper-0.2.38}/database_wrapper/utils/dataclass_addons.py
RENAMED
|
File without changes
|
|
File without changes
|
{database_wrapper-0.2.33 → database_wrapper-0.2.38}/database_wrapper.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|