database-wrapper 0.2.32__tar.gz → 0.2.36__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.32 → database_wrapper-0.2.36}/PKG-INFO +6 -6
- {database_wrapper-0.2.32 → database_wrapper-0.2.36}/database_wrapper/abc.py +6 -1
- {database_wrapper-0.2.32 → database_wrapper-0.2.36}/database_wrapper/config.py +3 -3
- {database_wrapper-0.2.32 → database_wrapper-0.2.36}/database_wrapper/db_backend.py +10 -4
- {database_wrapper-0.2.32 → database_wrapper-0.2.36}/database_wrapper/db_data_model.py +3 -0
- {database_wrapper-0.2.32 → database_wrapper-0.2.36}/database_wrapper/db_introspector.py +27 -18
- {database_wrapper-0.2.32 → database_wrapper-0.2.36}/database_wrapper/db_wrapper.py +15 -11
- {database_wrapper-0.2.32 → database_wrapper-0.2.36}/database_wrapper/db_wrapper_async.py +15 -11
- {database_wrapper-0.2.32 → database_wrapper-0.2.36}/database_wrapper/db_wrapper_mixin.py +89 -24
- {database_wrapper-0.2.32 → database_wrapper-0.2.36}/database_wrapper/serialization.py +17 -6
- {database_wrapper-0.2.32 → database_wrapper-0.2.36}/database_wrapper.egg-info/PKG-INFO +6 -6
- {database_wrapper-0.2.32 → database_wrapper-0.2.36}/database_wrapper.egg-info/requires.txt +5 -5
- {database_wrapper-0.2.32 → database_wrapper-0.2.36}/pyproject.toml +6 -6
- {database_wrapper-0.2.32 → database_wrapper-0.2.36}/README.md +0 -0
- {database_wrapper-0.2.32 → database_wrapper-0.2.36}/database_wrapper/__init__.py +0 -0
- {database_wrapper-0.2.32 → database_wrapper-0.2.36}/database_wrapper/common.py +0 -0
- {database_wrapper-0.2.32 → database_wrapper-0.2.36}/database_wrapper/py.typed +0 -0
- {database_wrapper-0.2.32 → database_wrapper-0.2.36}/database_wrapper/utils/__init__.py +0 -0
- {database_wrapper-0.2.32 → database_wrapper-0.2.36}/database_wrapper/utils/dataclass_addons.py +0 -0
- {database_wrapper-0.2.32 → database_wrapper-0.2.36}/database_wrapper.egg-info/SOURCES.txt +0 -0
- {database_wrapper-0.2.32 → database_wrapper-0.2.36}/database_wrapper.egg-info/dependency_links.txt +0 -0
- {database_wrapper-0.2.32 → database_wrapper-0.2.36}/database_wrapper.egg-info/top_level.txt +0 -0
- {database_wrapper-0.2.32 → database_wrapper-0.2.36}/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.36
|
|
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.36; extra == "pgsql"
|
|
37
37
|
Provides-Extra: mysql
|
|
38
|
-
Requires-Dist: database_wrapper_mysql==0.2.
|
|
38
|
+
Requires-Dist: database_wrapper_mysql==0.2.36; extra == "mysql"
|
|
39
39
|
Provides-Extra: mssql
|
|
40
|
-
Requires-Dist: database_wrapper_mssql==0.2.
|
|
40
|
+
Requires-Dist: database_wrapper_mssql==0.2.36; extra == "mssql"
|
|
41
41
|
Provides-Extra: sqlite
|
|
42
|
-
Requires-Dist: database_wrapper_sqlite==0.2.
|
|
42
|
+
Requires-Dist: database_wrapper_sqlite==0.2.36; extra == "sqlite"
|
|
43
43
|
Provides-Extra: redis
|
|
44
|
-
Requires-Dist: database_wrapper_redis==0.2.
|
|
44
|
+
Requires-Dist: database_wrapper_redis==0.2.36; 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
|
|
@@ -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
|
|
|
@@ -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": "13ed062c3bf6473d265176105620e06bba8b2f87",
|
|
7
|
+
"git_commit_date": "02.07.2026 02:03",
|
|
8
|
+
"app_version": "0.2.36",
|
|
9
9
|
}
|
|
@@ -104,11 +104,17 @@ class DatabaseBackend:
|
|
|
104
104
|
self.close_pool()
|
|
105
105
|
|
|
106
106
|
# Clean just in case
|
|
107
|
-
|
|
108
|
-
|
|
107
|
+
if hasattr(self, "connection"):
|
|
108
|
+
del self.connection
|
|
109
109
|
|
|
110
|
-
|
|
111
|
-
|
|
110
|
+
if hasattr(self, "cursor"):
|
|
111
|
+
del self.cursor
|
|
112
|
+
|
|
113
|
+
if hasattr(self, "pool"):
|
|
114
|
+
del self.pool
|
|
115
|
+
|
|
116
|
+
if hasattr(self, "pool_async"):
|
|
117
|
+
del self.pool_async
|
|
112
118
|
|
|
113
119
|
###############
|
|
114
120
|
### 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,8 +1,12 @@
|
|
|
1
1
|
import logging
|
|
2
|
+
import re
|
|
2
3
|
from typing import Any, cast
|
|
3
4
|
|
|
4
5
|
from .common import DataModelType, NoParam, OrderByItem
|
|
5
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_]*)*$")
|
|
9
|
+
|
|
6
10
|
|
|
7
11
|
class DBWrapperMixin:
|
|
8
12
|
"""
|
|
@@ -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,25 @@ 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
|
+
Args:
|
|
107
|
+
name (str): The identifier to validate.
|
|
108
|
+
|
|
109
|
+
Returns:
|
|
110
|
+
str: The validated identifier.
|
|
111
|
+
"""
|
|
112
|
+
if not isinstance(name, str) or not IDENTIFIER_PATTERN.match(name):
|
|
113
|
+
raise ValueError(f"Invalid SQL identifier: {name!r}")
|
|
114
|
+
|
|
115
|
+
return name
|
|
116
|
+
|
|
86
117
|
def make_identifier(self, schema: str | None, name: str) -> Any:
|
|
87
118
|
"""
|
|
88
119
|
Creates a SQL identifier object from the given name.
|
|
@@ -94,7 +125,9 @@ class DBWrapperMixin:
|
|
|
94
125
|
Returns:
|
|
95
126
|
str: The created SQL identifier object.
|
|
96
127
|
"""
|
|
128
|
+
self.validate_identifier(name)
|
|
97
129
|
if schema:
|
|
130
|
+
self.validate_identifier(schema)
|
|
98
131
|
return f"{schema}.{name}"
|
|
99
132
|
|
|
100
133
|
return name
|
|
@@ -169,9 +202,28 @@ class DBWrapperMixin:
|
|
|
169
202
|
if order_by is None:
|
|
170
203
|
return None
|
|
171
204
|
|
|
172
|
-
order_list = [f"{item[0]} {
|
|
205
|
+
order_list = [f"{self.validate_identifier(item[0])} {self.order_direction(item)}" for item in order_by]
|
|
173
206
|
return "ORDER BY {}".format(", ".join(order_list))
|
|
174
207
|
|
|
208
|
+
def order_direction(self, item: tuple[str, str | None] | tuple[str]) -> str:
|
|
209
|
+
"""
|
|
210
|
+
Extracts and validates the sort direction from an order-by item.
|
|
211
|
+
|
|
212
|
+
Args:
|
|
213
|
+
item (tuple): The order-by item (column, direction).
|
|
214
|
+
|
|
215
|
+
Returns:
|
|
216
|
+
str: "ASC" or "DESC".
|
|
217
|
+
"""
|
|
218
|
+
if len(item) < 2 or item[1] is None:
|
|
219
|
+
return "ASC"
|
|
220
|
+
|
|
221
|
+
direction = str(item[1]).upper()
|
|
222
|
+
if direction not in ("ASC", "DESC"):
|
|
223
|
+
raise ValueError(f"Invalid sort direction: {item[1]!r}")
|
|
224
|
+
|
|
225
|
+
return direction
|
|
226
|
+
|
|
175
227
|
def limit_query(self, offset: int = 0, limit: int = 100) -> Any | None:
|
|
176
228
|
"""
|
|
177
229
|
Creates a SQL query to limit the number of results returned.
|
|
@@ -186,42 +238,51 @@ class DBWrapperMixin:
|
|
|
186
238
|
if limit == 0:
|
|
187
239
|
return None
|
|
188
240
|
|
|
189
|
-
return f"LIMIT {limit} OFFSET {offset}"
|
|
241
|
+
return f"LIMIT {int(limit)} OFFSET {int(offset)}"
|
|
190
242
|
|
|
191
243
|
def format_filter(self, key: str, filter: Any) -> tuple[Any, ...]:
|
|
244
|
+
self.validate_identifier(key)
|
|
245
|
+
ph = self.placeholder
|
|
246
|
+
|
|
192
247
|
if type(filter) is dict:
|
|
193
248
|
if "$contains" in filter:
|
|
194
249
|
return (
|
|
195
|
-
f"{key} LIKE
|
|
250
|
+
f"{key} LIKE {ph}",
|
|
196
251
|
f"%{filter['$contains']}%",
|
|
197
252
|
)
|
|
198
253
|
elif "$starts_with" in filter:
|
|
199
|
-
return (f"{key} LIKE
|
|
254
|
+
return (f"{key} LIKE {ph}", f"{filter['$starts_with']}%")
|
|
200
255
|
elif "$ends_with" in filter:
|
|
201
|
-
return (f"{key} LIKE
|
|
256
|
+
return (f"{key} LIKE {ph}", f"%{filter['$ends_with']}")
|
|
202
257
|
elif "$min" in filter and "$max" not in filter:
|
|
203
|
-
return (f"{key} >=
|
|
258
|
+
return (f"{key} >= {ph}", filter["$min"])
|
|
204
259
|
elif "$max" in filter and "$min" not in filter:
|
|
205
|
-
return (f"{key} <=
|
|
260
|
+
return (f"{key} <= {ph}", filter["$max"])
|
|
206
261
|
elif "$min" in filter and "$max" in filter:
|
|
207
|
-
return (f"{key} BETWEEN
|
|
262
|
+
return (f"{key} BETWEEN {ph} AND {ph}", filter["$min"], filter["$max"])
|
|
208
263
|
elif "$in" in filter:
|
|
209
264
|
in_filter_1: list[Any] = cast(list[Any], filter["$in"])
|
|
210
|
-
|
|
265
|
+
if not in_filter_1:
|
|
266
|
+
# Empty IN list matches nothing
|
|
267
|
+
return ("1 = 0",)
|
|
268
|
+
return (f"{key} IN ({', '.join([ph] * len(in_filter_1))})",) + tuple(in_filter_1)
|
|
211
269
|
elif "$not_in" in filter:
|
|
212
270
|
in_filter_2: list[Any] = cast(list[Any], filter["$not_in"])
|
|
213
|
-
|
|
271
|
+
if not in_filter_2:
|
|
272
|
+
# Empty NOT IN list matches everything
|
|
273
|
+
return ("1 = 1",)
|
|
274
|
+
return (f"{key} NOT IN ({', '.join([ph] * len(in_filter_2))})",) + tuple(in_filter_2)
|
|
214
275
|
elif "$not" in filter:
|
|
215
|
-
return (f"{key} !=
|
|
276
|
+
return (f"{key} != {ph}", filter["$not"])
|
|
216
277
|
|
|
217
278
|
elif "$gt" in filter:
|
|
218
|
-
return (f"{key} >
|
|
279
|
+
return (f"{key} > {ph}", filter["$gt"])
|
|
219
280
|
elif "$gte" in filter:
|
|
220
|
-
return (f"{key} >=
|
|
281
|
+
return (f"{key} >= {ph}", filter["$gte"])
|
|
221
282
|
elif "$lt" in filter:
|
|
222
|
-
return (f"{key} <
|
|
283
|
+
return (f"{key} < {ph}", filter["$lt"])
|
|
223
284
|
elif "$lte" in filter:
|
|
224
|
-
return (f"{key} <=
|
|
285
|
+
return (f"{key} <= {ph}", filter["$lte"])
|
|
225
286
|
elif "$is_null" in filter:
|
|
226
287
|
return (f"{key} IS NULL",)
|
|
227
288
|
elif "$is_not_null" in filter:
|
|
@@ -229,7 +290,7 @@ class DBWrapperMixin:
|
|
|
229
290
|
|
|
230
291
|
raise NotImplementedError("Filter type not supported")
|
|
231
292
|
elif isinstance(filter, (bool, str, int, float)):
|
|
232
|
-
return (f"{key} =
|
|
293
|
+
return (f"{key} = {ph}", filter)
|
|
233
294
|
else:
|
|
234
295
|
raise NotImplementedError(f"Filter type not supported: {key} = {type(filter)}")
|
|
235
296
|
|
|
@@ -268,9 +329,13 @@ class DBWrapperMixin:
|
|
|
268
329
|
keys = store_data.keys()
|
|
269
330
|
values = list(store_data.values())
|
|
270
331
|
|
|
271
|
-
columns = ", ".join(keys)
|
|
272
|
-
values_placeholder = ", ".join([
|
|
273
|
-
|
|
332
|
+
columns = ", ".join(self.validate_identifier(key) for key in keys)
|
|
333
|
+
values_placeholder = ", ".join([self.placeholder] * len(values))
|
|
334
|
+
query = f"INSERT INTO {table_identifier} ({columns}) VALUES ({values_placeholder})"
|
|
335
|
+
if self.insert_returning:
|
|
336
|
+
query += f" RETURNING {return_key}"
|
|
337
|
+
|
|
338
|
+
return query
|
|
274
339
|
|
|
275
340
|
def _format_update_query(
|
|
276
341
|
self,
|
|
@@ -279,12 +344,12 @@ class DBWrapperMixin:
|
|
|
279
344
|
update_data: dict[str, Any],
|
|
280
345
|
) -> Any:
|
|
281
346
|
keys = update_data.keys()
|
|
282
|
-
set_clause = ", ".join(f"{key} =
|
|
283
|
-
return f"UPDATE {table_identifier} SET {set_clause} WHERE {update_key} =
|
|
347
|
+
set_clause = ", ".join(f"{self.validate_identifier(key)} = {self.placeholder}" for key in keys)
|
|
348
|
+
return f"UPDATE {table_identifier} SET {set_clause} WHERE {update_key} = {self.placeholder}"
|
|
284
349
|
|
|
285
350
|
def _format_delete_query(
|
|
286
351
|
self,
|
|
287
352
|
table_identifier: Any,
|
|
288
353
|
delete_key: Any,
|
|
289
354
|
) -> Any:
|
|
290
|
-
return f"DELETE FROM {table_identifier} WHERE {delete_key} =
|
|
355
|
+
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.36
|
|
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.36; extra == "pgsql"
|
|
37
37
|
Provides-Extra: mysql
|
|
38
|
-
Requires-Dist: database_wrapper_mysql==0.2.
|
|
38
|
+
Requires-Dist: database_wrapper_mysql==0.2.36; extra == "mysql"
|
|
39
39
|
Provides-Extra: mssql
|
|
40
|
-
Requires-Dist: database_wrapper_mssql==0.2.
|
|
40
|
+
Requires-Dist: database_wrapper_mssql==0.2.36; extra == "mssql"
|
|
41
41
|
Provides-Extra: sqlite
|
|
42
|
-
Requires-Dist: database_wrapper_sqlite==0.2.
|
|
42
|
+
Requires-Dist: database_wrapper_sqlite==0.2.36; extra == "sqlite"
|
|
43
43
|
Provides-Extra: redis
|
|
44
|
-
Requires-Dist: database_wrapper_redis==0.2.
|
|
44
|
+
Requires-Dist: database_wrapper_redis==0.2.36; 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.36
|
|
21
21
|
|
|
22
22
|
[mysql]
|
|
23
|
-
database_wrapper_mysql==0.2.
|
|
23
|
+
database_wrapper_mysql==0.2.36
|
|
24
24
|
|
|
25
25
|
[pgsql]
|
|
26
|
-
database_wrapper_pgsql==0.2.
|
|
26
|
+
database_wrapper_pgsql==0.2.36
|
|
27
27
|
|
|
28
28
|
[redis]
|
|
29
|
-
database_wrapper_redis==0.2.
|
|
29
|
+
database_wrapper_redis==0.2.36
|
|
30
30
|
|
|
31
31
|
[sqlite]
|
|
32
|
-
database_wrapper_sqlite==0.2.
|
|
32
|
+
database_wrapper_sqlite==0.2.36
|
|
@@ -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.36"
|
|
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.36"]
|
|
56
|
+
mysql = ["database_wrapper_mysql == 0.2.36"]
|
|
57
|
+
mssql = ["database_wrapper_mssql == 0.2.36"]
|
|
58
|
+
sqlite = ["database_wrapper_sqlite == 0.2.36"]
|
|
59
|
+
redis = ["database_wrapper_redis == 0.2.36"]
|
|
60
60
|
all = ["database_wrapper[pgsql,mysql,mssql,sqlite,redis]"]
|
|
61
61
|
dev = [
|
|
62
62
|
# Development
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{database_wrapper-0.2.32 → database_wrapper-0.2.36}/database_wrapper/utils/dataclass_addons.py
RENAMED
|
File without changes
|
|
File without changes
|
{database_wrapper-0.2.32 → database_wrapper-0.2.36}/database_wrapper.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|