slinn-orm 0.0.3__tar.gz → 0.0.5__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.
- {slinn_orm-0.0.3/slinn_orm.egg-info → slinn_orm-0.0.5}/PKG-INFO +1 -1
- {slinn_orm-0.0.3 → slinn_orm-0.0.5}/orm/__init__.py +3 -3
- slinn_orm-0.0.5/orm/models.py +167 -0
- {slinn_orm-0.0.3 → slinn_orm-0.0.5}/orm/postgres/__init__.py +70 -32
- {slinn_orm-0.0.3 → slinn_orm-0.0.5}/orm/sqlite/__init__.py +69 -29
- {slinn_orm-0.0.3 → slinn_orm-0.0.5}/pyproject.toml +1 -5
- {slinn_orm-0.0.3 → slinn_orm-0.0.5/slinn_orm.egg-info}/PKG-INFO +1 -1
- slinn_orm-0.0.3/orm/models.py +0 -97
- {slinn_orm-0.0.3 → slinn_orm-0.0.5}/LICENSE +0 -0
- {slinn_orm-0.0.3 → slinn_orm-0.0.5}/orm/attributed_dict.py +0 -0
- {slinn_orm-0.0.3 → slinn_orm-0.0.5}/orm/order.py +0 -0
- {slinn_orm-0.0.3 → slinn_orm-0.0.5}/orm/typemap.py +0 -0
- {slinn_orm-0.0.3 → slinn_orm-0.0.5}/setup.cfg +0 -0
- {slinn_orm-0.0.3 → slinn_orm-0.0.5}/slinn_orm.egg-info/SOURCES.txt +0 -0
- {slinn_orm-0.0.3 → slinn_orm-0.0.5}/slinn_orm.egg-info/dependency_links.txt +0 -0
- {slinn_orm-0.0.3 → slinn_orm-0.0.5}/slinn_orm.egg-info/requires.txt +0 -0
- {slinn_orm-0.0.3 → slinn_orm-0.0.5}/slinn_orm.egg-info/top_level.txt +0 -0
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
from
|
|
2
|
-
from typing import Protocol, Coroutine
|
|
1
|
+
from typing import Protocol, Coroutine, Self
|
|
3
2
|
from .order import Order
|
|
4
3
|
from .models import Model
|
|
5
4
|
import re
|
|
@@ -12,6 +11,7 @@ class CollectionProtocol(Protocol):
|
|
|
12
11
|
async def find(self, _filter: dict, *, fields: tuple[str] = ('*',)) -> list[dict]: ...
|
|
13
12
|
async def find_one(self, _filter: dict, *, fields: tuple[str] = ('*',)) -> dict: ...
|
|
14
13
|
async def insert(self, _object: dict, *, returning: tuple[str] = (), typemap: dict | None = None) -> None: ...
|
|
14
|
+
async def insert_many(self, _objects: list[dict]) -> None: ...
|
|
15
15
|
async def update(self, _filter: dict, _object: dict, *, returning: tuple[str] = (), typemap: dict | None = None) -> None: ...
|
|
16
16
|
async def delete(self, _filter) -> None: ...
|
|
17
17
|
async def pop(self, _filter) -> dict: ...
|
|
@@ -21,7 +21,7 @@ class CollectionProtocol(Protocol):
|
|
|
21
21
|
|
|
22
22
|
|
|
23
23
|
class ConnectionProtocol(Protocol):
|
|
24
|
-
async def __aenter__(self) ->
|
|
24
|
+
async def __aenter__(self) -> Self: ...
|
|
25
25
|
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: ...
|
|
26
26
|
def __getattr__(self, key) -> CollectionProtocol: ...
|
|
27
27
|
def collection(self, key) -> CollectionProtocol: ...
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from typing import Literal, Optional
|
|
3
|
+
from datetime import timedelta, datetime
|
|
4
|
+
from typing import NamedTuple, Any
|
|
5
|
+
from ipaddress import IPv4Address, IPv6Address, ip_address
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Model(ABC):
|
|
9
|
+
@staticmethod
|
|
10
|
+
@abstractmethod
|
|
11
|
+
def __collection_name__() -> str: ...
|
|
12
|
+
|
|
13
|
+
@property
|
|
14
|
+
def __fields__(self) -> dict[str, Field]:
|
|
15
|
+
return {
|
|
16
|
+
field_name: field for field_name, field in self.__dict__.items()
|
|
17
|
+
if not field_name.startswith('_') and isinstance(field, Field)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
def _update_meta(self) -> None:
|
|
21
|
+
if not hasattr(self, '_meta_primary_keys'):
|
|
22
|
+
self._meta_primary_keys = ()
|
|
23
|
+
|
|
24
|
+
for field_name, field in type(self).__dict__.items():
|
|
25
|
+
self.__dict__[field_name] = field
|
|
26
|
+
if field_name.startswith('_') or not isinstance(field, Field):
|
|
27
|
+
continue
|
|
28
|
+
if hasattr(field, 'primary') and field.primary and field_name not in self._meta_primary_keys:
|
|
29
|
+
self._meta_primary_keys = (*self._meta_primary_keys, field_name)
|
|
30
|
+
|
|
31
|
+
def __serialize_object__(self, obj: dict[str, Any]) -> dict[str, Any]:
|
|
32
|
+
result = obj.copy()
|
|
33
|
+
for field_name in result:
|
|
34
|
+
field = self.__fields__.get(field_name)
|
|
35
|
+
if not field:
|
|
36
|
+
continue
|
|
37
|
+
result[field_name] = field.__serialize__(result[field_name])
|
|
38
|
+
return result
|
|
39
|
+
|
|
40
|
+
def __deserialize_object__(self, obj: Any) -> dict[str, Any]:
|
|
41
|
+
result = {}
|
|
42
|
+
for field_name in dict(obj):
|
|
43
|
+
field = self.__fields__.get(field_name)
|
|
44
|
+
if not field:
|
|
45
|
+
continue
|
|
46
|
+
result[field_name] = field.__deserialize__(obj[field_name])
|
|
47
|
+
return result
|
|
48
|
+
|
|
49
|
+
def __new__(cls, **kwargs):
|
|
50
|
+
if kwargs:
|
|
51
|
+
return cls().__serialize_object__(kwargs)
|
|
52
|
+
return object.__new__(cls)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class Field(ABC):
|
|
56
|
+
class FieldReference(NamedTuple):
|
|
57
|
+
collection_name: str
|
|
58
|
+
field_name: str
|
|
59
|
+
|
|
60
|
+
def __serialize__(self, value: Any) -> Any:
|
|
61
|
+
return value
|
|
62
|
+
|
|
63
|
+
def __deserialize__(self, value: Any) -> Any:
|
|
64
|
+
return value
|
|
65
|
+
|
|
66
|
+
def make_identity(self) -> Field:
|
|
67
|
+
self.identity = True
|
|
68
|
+
return self
|
|
69
|
+
|
|
70
|
+
def make_primary(self) -> Field:
|
|
71
|
+
self.primary = True
|
|
72
|
+
return self
|
|
73
|
+
|
|
74
|
+
def make_unique(self) -> Field:
|
|
75
|
+
self.unique = True
|
|
76
|
+
return self
|
|
77
|
+
|
|
78
|
+
def make_not_null(self) -> Field:
|
|
79
|
+
self.not_null = True
|
|
80
|
+
return self
|
|
81
|
+
|
|
82
|
+
def set_reference(self, collection_name: str, field_name: str) -> Field:
|
|
83
|
+
self.reference = self.FieldReference(collection_name, field_name)
|
|
84
|
+
return self
|
|
85
|
+
|
|
86
|
+
def set_default_expr(self, default_expr: str) -> Field:
|
|
87
|
+
self.default_expr = default_expr
|
|
88
|
+
return self
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class BoolField(Field): ...
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class IntegerField(Field):
|
|
95
|
+
def __init__(self, *, size: Literal[2, 4, 8] = 4):
|
|
96
|
+
self.size = size
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class DecimalField(Field): ...
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class FloatField(Field):
|
|
103
|
+
def __init__(self, *, double: bool = False):
|
|
104
|
+
self.double = double
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class TextField(Field): ...
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class TimeField(Field):
|
|
111
|
+
def __init__(
|
|
112
|
+
self,
|
|
113
|
+
*,
|
|
114
|
+
zone: bool = True,
|
|
115
|
+
date: bool = True,
|
|
116
|
+
time: bool = True,
|
|
117
|
+
default: timedelta | datetime | None
|
|
118
|
+
):
|
|
119
|
+
self.zone = zone
|
|
120
|
+
self.date = date
|
|
121
|
+
self.time = time
|
|
122
|
+
self.default = default
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class TimeDeltaField(Field): ...
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class BinaryField(Field): ...
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class UIDField(Field):
|
|
132
|
+
def __init__(self):
|
|
133
|
+
self.make_identity()
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class UUIDField(Field):
|
|
137
|
+
def __init__(self):
|
|
138
|
+
self.set_default_expr("""
|
|
139
|
+
(
|
|
140
|
+
unhex(
|
|
141
|
+
hex(
|
|
142
|
+
unhex(
|
|
143
|
+
substr(
|
|
144
|
+
hex(zeroblob(8) || printf('%016X', CAST(unixepoch('subsecond') * 1000 AS INTEGER))), -12
|
|
145
|
+
)
|
|
146
|
+
)
|
|
147
|
+
)
|
|
148
|
+
||
|
|
149
|
+
'7' || substr(hex(randomblob(2)), 2, 3)
|
|
150
|
+
||
|
|
151
|
+
substr('89AB', 1 + (abs(random()) % 4), 1) || substr(hex(randomblob(8)), 2)
|
|
152
|
+
)
|
|
153
|
+
)
|
|
154
|
+
""")
|
|
155
|
+
|
|
156
|
+
class InetField(Field):
|
|
157
|
+
def __serialize__(self, ip: IPv4Address | IPv6Address | str | int) -> bytes:
|
|
158
|
+
if isinstance(ip, str):
|
|
159
|
+
ip = ip_address(ip)
|
|
160
|
+
return ip.packed
|
|
161
|
+
|
|
162
|
+
def __deserialize__(self, ip: IPv4Address | IPv6Address | str | int | bytes) -> IPv4Address | IPv6Address:
|
|
163
|
+
if isinstance(ip, (IPv4Address, IPv6Address)):
|
|
164
|
+
return ip
|
|
165
|
+
if isinstance(ip, (str, int, bytes)):
|
|
166
|
+
return ip_address(ip)
|
|
167
|
+
|
|
@@ -1,20 +1,22 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
1
|
from .. import CollectionProtocol, ConnectionProtocol, PoolProtocol
|
|
3
|
-
from ..attributed_dict import AttributedDict
|
|
4
2
|
from ..typemap import typemap as tm
|
|
5
3
|
from ..order import OrderType
|
|
6
|
-
from ..models import (
|
|
7
|
-
|
|
8
|
-
|
|
4
|
+
from ..models import (
|
|
5
|
+
Model, Field, BoolField, IntegerField, DecimalField, FloatField, TextField, TimeField, TimeDeltaField,
|
|
6
|
+
BinaryField, UIDField, UUIDField, InetField
|
|
7
|
+
)
|
|
8
|
+
from typing import Coroutine, Optional, Final, Iterable, Sequence, Any
|
|
9
9
|
from functools import partial
|
|
10
10
|
from datetime import datetime, timedelta
|
|
11
11
|
import asyncpg
|
|
12
|
+
import asyncio
|
|
12
13
|
|
|
13
14
|
|
|
14
15
|
class PostgresCollection(CollectionProtocol):
|
|
15
|
-
def __init__(self, connection: PostgresConnection, name: str):
|
|
16
|
+
def __init__(self, connection: PostgresConnection, name: str, model: Model | None = None):
|
|
16
17
|
self.connection = connection
|
|
17
18
|
self.name = name
|
|
19
|
+
self.model = model
|
|
18
20
|
|
|
19
21
|
async def find(
|
|
20
22
|
self,
|
|
@@ -22,7 +24,7 @@ class PostgresCollection(CollectionProtocol):
|
|
|
22
24
|
*,
|
|
23
25
|
fields: tuple[str] = ('*',),
|
|
24
26
|
order: tuple[tuple[OrderType, str]] = ()) -> list[dict]:
|
|
25
|
-
return [
|
|
27
|
+
return [self.model.__deserialize_object__(record) for record in await self.connection._fetch(
|
|
26
28
|
f'SELECT {', '.join(fields)} '
|
|
27
29
|
f'FROM {self.name} '
|
|
28
30
|
f'{'WHERE ' if _filter else ''}{' AND '.join([f'{list(_filter.keys())[i]}=${i+1}' for i in range(0, len(_filter))])} '
|
|
@@ -48,12 +50,31 @@ class PostgresCollection(CollectionProtocol):
|
|
|
48
50
|
typemap: dict | None = None) -> None:
|
|
49
51
|
if not _object:
|
|
50
52
|
return []
|
|
53
|
+
if self.model:
|
|
54
|
+
_object = self.model.__serialize_object__(_object)
|
|
51
55
|
records = await self.connection._fetch(
|
|
52
56
|
f'INSERT INTO {self.name}({', '.join(_object.keys())}) '
|
|
53
|
-
f'VALUES({', '.join([f'${i+1}' for i in range(
|
|
57
|
+
f'VALUES({', '.join([f'${i+1}' for i in range(len(_object))])}) '
|
|
54
58
|
f'{'RETURNING' if returning else ''} {', '.join(returning)}',
|
|
55
59
|
*tm(_object, typemap).values())
|
|
56
60
|
return records[0] if records else None
|
|
61
|
+
|
|
62
|
+
async def insert_many(
|
|
63
|
+
self,
|
|
64
|
+
_objects: list[dict]
|
|
65
|
+
) -> int:
|
|
66
|
+
if not _objects:
|
|
67
|
+
return 0
|
|
68
|
+
if self.model:
|
|
69
|
+
for i, _object in enumerate(_objects):
|
|
70
|
+
_objects[i] = self.model.__serialize_object__(_object)
|
|
71
|
+
|
|
72
|
+
columns = ", ".join(_objects[0])
|
|
73
|
+
placeholders = ", ".join(["?"] * len(_objects[0]))
|
|
74
|
+
|
|
75
|
+
query = f"INSERT INTO {self.name}({columns}) VALUES({placeholders})"
|
|
76
|
+
return await self.connection._executemany(query, [list(_object.values()) for _object in _objects])
|
|
77
|
+
|
|
57
78
|
|
|
58
79
|
async def update(
|
|
59
80
|
self,
|
|
@@ -64,6 +85,8 @@ class PostgresCollection(CollectionProtocol):
|
|
|
64
85
|
typemap: dict | None = None) -> None:
|
|
65
86
|
if not _object:
|
|
66
87
|
return []
|
|
88
|
+
if self.model:
|
|
89
|
+
_object = self.model.__serialize_object__(_object)
|
|
67
90
|
return await self.connection._fetch(
|
|
68
91
|
f'UPDATE {self.name} '
|
|
69
92
|
f'SET {', '.join([f'{key}=${i+1}' for i, key in enumerate(_object)])} '
|
|
@@ -94,6 +117,7 @@ class PostgresCollection(CollectionProtocol):
|
|
|
94
117
|
FROM {self.name}
|
|
95
118
|
{'WHERE ' if _filter else ''}{' AND '.join([f'{list(_filter.keys())[i]}=${i+1}' for i in range(0, len(_filter))])};''',
|
|
96
119
|
*_filter.values()))[0]['count']
|
|
120
|
+
|
|
97
121
|
async def get_size(self) -> int: ...
|
|
98
122
|
|
|
99
123
|
async def drop(self, *, not_exists_ok: bool = False) -> None:
|
|
@@ -127,18 +151,22 @@ class PostgresConnection(ConnectionProtocol):
|
|
|
127
151
|
TimeDeltaField: lambda field: 'INTERVAL',
|
|
128
152
|
BinaryField: lambda field: 'BYTEA',
|
|
129
153
|
UIDField: lambda field: 'BIGINT',
|
|
130
|
-
UUIDField: lambda field: 'UUID'
|
|
154
|
+
UUIDField: lambda field: 'UUID',
|
|
155
|
+
InetField: lambda field: 'INET'
|
|
131
156
|
}
|
|
132
157
|
|
|
133
|
-
def __init__(self, pool, connection, transaction, autocommit=True):
|
|
158
|
+
def __init__(self, pool, connection, transaction, autocommit: bool = True):
|
|
134
159
|
self._pool = pool
|
|
135
160
|
self._connection = connection
|
|
136
161
|
self._transaction = transaction
|
|
137
162
|
self._autocommit = autocommit
|
|
163
|
+
self._models = set()
|
|
138
164
|
self.collection = self.__getattr__
|
|
139
165
|
|
|
140
166
|
def __getattr__(self, key) -> CollectionProtocol:
|
|
141
|
-
return PostgresCollection(
|
|
167
|
+
return PostgresCollection(
|
|
168
|
+
self, key, model = next(iter(model for model in self._models if model.__collection_name__() == key))
|
|
169
|
+
)
|
|
142
170
|
|
|
143
171
|
async def rollback(self) -> None:
|
|
144
172
|
await self._transaction.rollback()
|
|
@@ -154,9 +182,9 @@ class PostgresConnection(ConnectionProtocol):
|
|
|
154
182
|
ORDER BY table_name;''')]
|
|
155
183
|
|
|
156
184
|
async def create(self, model: Model, *, exists_ok=False) -> None:
|
|
157
|
-
model._update_meta(
|
|
185
|
+
model._update_meta()
|
|
158
186
|
fields = []
|
|
159
|
-
for field_name in model.__dict__
|
|
187
|
+
for field_name in model.__dict__:
|
|
160
188
|
field = getattr(model, field_name)
|
|
161
189
|
if field_name.startswith('_') or not isinstance(field, Field):
|
|
162
190
|
continue
|
|
@@ -167,7 +195,8 @@ class PostgresConnection(ConnectionProtocol):
|
|
|
167
195
|
{'NOT NULL' if hasattr(field, 'not_null') and field.not_null else ''}
|
|
168
196
|
{'GENERATED ALWAYS AS IDENTITY' if hasattr(field, 'identity') and field.identity else ''}
|
|
169
197
|
{f'REFERENCES {field.reference.collection_name}({field.reference.field_name})'
|
|
170
|
-
|
|
198
|
+
if hasattr(field, 'reference') and field.reference else ''}
|
|
199
|
+
{f'DEFAULT {field.default_expr}' if hasattr(field, 'default_expr') else ''}
|
|
171
200
|
'''.strip()
|
|
172
201
|
)
|
|
173
202
|
await self._fetch(f'''
|
|
@@ -176,6 +205,7 @@ class PostgresConnection(ConnectionProtocol):
|
|
|
176
205
|
{f'PRIMARY KEY ({','.join(model._meta_primary_keys)})' if model._meta_primary_keys else ''}
|
|
177
206
|
);
|
|
178
207
|
'''.strip())
|
|
208
|
+
self._models.add(model)
|
|
179
209
|
|
|
180
210
|
async def create_index(
|
|
181
211
|
self,
|
|
@@ -186,9 +216,6 @@ class PostgresConnection(ConnectionProtocol):
|
|
|
186
216
|
exists_ok: bool=False,
|
|
187
217
|
unique: bool=False
|
|
188
218
|
) -> None:
|
|
189
|
-
print(f"""
|
|
190
|
-
CREATE {'UNIQUE ' if unique else ''}INDEX {'IF NOT EXISTS ' if exists_ok else ''}{index_name} ON {collection_name}({','.join(fields)});
|
|
191
|
-
""")
|
|
192
219
|
await self._fetch(f'''
|
|
193
220
|
CREATE {'UNIQUE ' if unique else ''}INDEX {'IF NOT EXISTS ' if exists_ok else ''}{index_name} ON {collection_name}({','.join(fields)});
|
|
194
221
|
''')
|
|
@@ -214,6 +241,17 @@ class PostgresConnection(ConnectionProtocol):
|
|
|
214
241
|
timeout=timeout,
|
|
215
242
|
record_class=record_class
|
|
216
243
|
)
|
|
244
|
+
|
|
245
|
+
async def _executemany(
|
|
246
|
+
self,
|
|
247
|
+
query: str,
|
|
248
|
+
params_seq: Iterable[Sequence[Any]],
|
|
249
|
+
*,
|
|
250
|
+
timeout: float | None = None,
|
|
251
|
+
):
|
|
252
|
+
query = " ".join(line.strip() for line in query.split("\n")).strip()
|
|
253
|
+
async with asyncio.timeout(timeout):
|
|
254
|
+
await self._connection.executemany(query, params_seq)
|
|
217
255
|
|
|
218
256
|
class PostgresPool(PoolProtocol):
|
|
219
257
|
def __init__(self, pool_factory, autocommit=True):
|
|
@@ -245,28 +283,28 @@ class PostgresPool(PoolProtocol):
|
|
|
245
283
|
|
|
246
284
|
|
|
247
285
|
def Postgres(
|
|
248
|
-
dsn:
|
|
286
|
+
dsn: str | None = None,
|
|
249
287
|
*,
|
|
250
|
-
host:
|
|
251
|
-
port:
|
|
252
|
-
user:
|
|
253
|
-
password:
|
|
254
|
-
database:
|
|
255
|
-
server_settings:
|
|
288
|
+
host: str | None = None,
|
|
289
|
+
port: int | None = None,
|
|
290
|
+
user: str | None = None,
|
|
291
|
+
password: str | None = None,
|
|
292
|
+
database: str | None = None,
|
|
293
|
+
server_settings: dict | None = None,
|
|
256
294
|
autocommit: bool = True) -> PostgresPool:
|
|
257
295
|
return PostgresPool(
|
|
258
296
|
partial(
|
|
259
297
|
asyncpg.create_pool,
|
|
260
298
|
dsn,
|
|
261
|
-
server_settings=server_settings
|
|
299
|
+
server_settings = server_settings
|
|
262
300
|
) if dsn else partial(
|
|
263
301
|
asyncpg.create_pool,
|
|
264
|
-
host=host,
|
|
265
|
-
port=port,
|
|
266
|
-
user=user,
|
|
267
|
-
password=password,
|
|
268
|
-
database=database,
|
|
269
|
-
server_settings=server_settings
|
|
302
|
+
host = host,
|
|
303
|
+
port = port,
|
|
304
|
+
user = user,
|
|
305
|
+
password = password,
|
|
306
|
+
database = database,
|
|
307
|
+
server_settings = server_settings
|
|
270
308
|
),
|
|
271
|
-
autocommit=autocommit
|
|
309
|
+
autocommit = autocommit
|
|
272
310
|
)
|
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
from
|
|
2
|
-
from functools import partial
|
|
3
|
-
from typing import Any, Coroutine, Optional, Final
|
|
1
|
+
from typing import Any, Coroutine, Final, Iterable, Sequence
|
|
4
2
|
from .. import CollectionProtocol, ConnectionProtocol, PoolProtocol
|
|
5
|
-
from ..attributed_dict import AttributedDict
|
|
6
3
|
from ..typemap import typemap as tm
|
|
7
4
|
from ..order import OrderType
|
|
8
|
-
from ..models import (
|
|
9
|
-
|
|
5
|
+
from ..models import (
|
|
6
|
+
Model, Field, BoolField, IntegerField, DecimalField, FloatField, TextField, TimeField, TimeDeltaField,
|
|
7
|
+
BinaryField, UIDField, UUIDField, InetField
|
|
8
|
+
)
|
|
10
9
|
from datetime import datetime, timedelta
|
|
11
10
|
import aiosqlite
|
|
12
11
|
import asyncio
|
|
13
12
|
|
|
14
13
|
|
|
15
14
|
class SQLiteCollection(CollectionProtocol):
|
|
16
|
-
def __init__(self, connection: SQLiteConnection, name: str):
|
|
15
|
+
def __init__(self, connection: SQLiteConnection, name: str, model: Model | None = None):
|
|
17
16
|
self.connection = connection
|
|
18
17
|
self.name = name
|
|
18
|
+
self.model = model
|
|
19
19
|
|
|
20
20
|
async def find(
|
|
21
21
|
self,
|
|
@@ -27,7 +27,7 @@ class SQLiteCollection(CollectionProtocol):
|
|
|
27
27
|
where_clause = ""
|
|
28
28
|
params = []
|
|
29
29
|
if _filter:
|
|
30
|
-
conditions = [f"{key} = ?" for key in _filter
|
|
30
|
+
conditions = [f"{key} = ?" for key in _filter]
|
|
31
31
|
where_clause = f"WHERE {' AND '.join(conditions)}"
|
|
32
32
|
params.extend(_filter.values())
|
|
33
33
|
|
|
@@ -41,11 +41,11 @@ class SQLiteCollection(CollectionProtocol):
|
|
|
41
41
|
|
|
42
42
|
query = f"SELECT {', '.join(fields)} FROM {self.name} {where_clause} {order_clause}"
|
|
43
43
|
rows = await self.connection._fetch(query, *params)
|
|
44
|
-
return [
|
|
44
|
+
return [self.model.__deserialize_object__(row) for row in rows]
|
|
45
45
|
|
|
46
46
|
async def find_one(
|
|
47
47
|
self, _filter: dict, *, fields: tuple[str] = ("*",)
|
|
48
|
-
) ->
|
|
48
|
+
) -> dict | None:
|
|
49
49
|
result = await self.find(_filter, fields=fields)
|
|
50
50
|
return result[0] if result else None
|
|
51
51
|
|
|
@@ -54,10 +54,12 @@ class SQLiteCollection(CollectionProtocol):
|
|
|
54
54
|
_object: dict,
|
|
55
55
|
*,
|
|
56
56
|
returning: tuple[str] = (),
|
|
57
|
-
typemap:
|
|
58
|
-
) ->
|
|
57
|
+
typemap: dict | None = None,
|
|
58
|
+
) -> dict | None:
|
|
59
59
|
if not _object:
|
|
60
60
|
return None
|
|
61
|
+
if self.model:
|
|
62
|
+
_object = self.model.__serialize_object__(_object)
|
|
61
63
|
|
|
62
64
|
data = tm(_object, typemap)
|
|
63
65
|
columns = ", ".join(data.keys())
|
|
@@ -70,24 +72,42 @@ class SQLiteCollection(CollectionProtocol):
|
|
|
70
72
|
rows = await self.connection._fetch(query, *data.values())
|
|
71
73
|
return rows[0] if rows else None
|
|
72
74
|
|
|
75
|
+
async def insert_many(
|
|
76
|
+
self,
|
|
77
|
+
_objects: list[dict]
|
|
78
|
+
) -> None:
|
|
79
|
+
if not _objects:
|
|
80
|
+
return 0
|
|
81
|
+
if self.model:
|
|
82
|
+
for i, _object in enumerate(_objects):
|
|
83
|
+
_objects[i] = self.model.__serialize_object__(_object)
|
|
84
|
+
|
|
85
|
+
columns = ", ".join(_objects[0])
|
|
86
|
+
placeholders = ", ".join(["?"] * len(_objects[0]))
|
|
87
|
+
|
|
88
|
+
query = f"INSERT INTO {self.name}({columns}) VALUES({placeholders})"
|
|
89
|
+
await self.connection._executemany(query, [list(_object.values()) for _object in _objects])
|
|
90
|
+
|
|
73
91
|
async def update(
|
|
74
92
|
self,
|
|
75
93
|
_filter: dict,
|
|
76
94
|
_object: dict,
|
|
77
95
|
*,
|
|
78
96
|
returning: tuple[str] = (),
|
|
79
|
-
typemap:
|
|
97
|
+
typemap: dict | None = None,
|
|
80
98
|
) -> list[dict]:
|
|
81
99
|
if not _object:
|
|
82
100
|
return []
|
|
101
|
+
if self.model:
|
|
102
|
+
_object = self.model.__serialize_object__(_object)
|
|
83
103
|
|
|
84
104
|
data = tm(_object, typemap)
|
|
85
|
-
set_clause = ", ".join([f"{key} = ?" for key in data
|
|
105
|
+
set_clause = ", ".join([f"{key} = ?" for key in data])
|
|
86
106
|
params = list(data.values())
|
|
87
107
|
|
|
88
108
|
where_clause = ""
|
|
89
109
|
if _filter:
|
|
90
|
-
conditions = [f"{key} = ?" for key in _filter
|
|
110
|
+
conditions = [f"{key} = ?" for key in _filter]
|
|
91
111
|
where_clause = f"WHERE {' AND '.join(conditions)}"
|
|
92
112
|
params.extend(_filter.values())
|
|
93
113
|
|
|
@@ -102,7 +122,7 @@ class SQLiteCollection(CollectionProtocol):
|
|
|
102
122
|
where_clause = ""
|
|
103
123
|
params = []
|
|
104
124
|
if _filter:
|
|
105
|
-
conditions = [f"{key} = ?" for key in _filter
|
|
125
|
+
conditions = [f"{key} = ?" for key in _filter]
|
|
106
126
|
where_clause = f"WHERE {' AND '.join(conditions)}"
|
|
107
127
|
params.extend(_filter.values())
|
|
108
128
|
|
|
@@ -111,11 +131,11 @@ class SQLiteCollection(CollectionProtocol):
|
|
|
111
131
|
|
|
112
132
|
async def pop(
|
|
113
133
|
self, _filter: dict, *, returning: tuple[str] = ("*",)
|
|
114
|
-
) ->
|
|
134
|
+
) -> dict | None:
|
|
115
135
|
where_clause = ""
|
|
116
136
|
params = []
|
|
117
137
|
if _filter:
|
|
118
|
-
conditions = [f"{key} = ?" for key in _filter
|
|
138
|
+
conditions = [f"{key} = ?" for key in _filter]
|
|
119
139
|
where_clause = f"WHERE {' AND '.join(conditions)}"
|
|
120
140
|
params.extend(_filter.values())
|
|
121
141
|
|
|
@@ -128,7 +148,7 @@ class SQLiteCollection(CollectionProtocol):
|
|
|
128
148
|
where_clause = ""
|
|
129
149
|
params = []
|
|
130
150
|
if _filter:
|
|
131
|
-
conditions = [f"{key} = ?" for key in _filter
|
|
151
|
+
conditions = [f"{key} = ?" for key in _filter]
|
|
132
152
|
where_clause = f"WHERE {' AND '.join(conditions)}"
|
|
133
153
|
params.extend(_filter.values())
|
|
134
154
|
|
|
@@ -168,7 +188,8 @@ class SQLiteConnection(ConnectionProtocol):
|
|
|
168
188
|
TimeDeltaField: lambda field: 'INTEGER',
|
|
169
189
|
BinaryField: lambda field: 'BLOB',
|
|
170
190
|
UIDField: lambda field: 'INTEGER',
|
|
171
|
-
UUIDField: lambda field: 'TEXT'
|
|
191
|
+
UUIDField: lambda field: 'TEXT',
|
|
192
|
+
InetField: lambda field: 'BLOB'
|
|
172
193
|
}
|
|
173
194
|
|
|
174
195
|
def __init__(self, pool: SQLitePool, connection: aiosqlite.Connection, autocommit: bool = True):
|
|
@@ -176,10 +197,13 @@ class SQLiteConnection(ConnectionProtocol):
|
|
|
176
197
|
self._connection = connection
|
|
177
198
|
self._autocommit = autocommit
|
|
178
199
|
self._in_transaction = False
|
|
200
|
+
self._models = set()
|
|
179
201
|
self.collection = self.__getattr__
|
|
180
202
|
|
|
181
203
|
def __getattr__(self, key) -> CollectionProtocol:
|
|
182
|
-
return SQLiteCollection(
|
|
204
|
+
return SQLiteCollection(
|
|
205
|
+
self, key, model = next(iter(model for model in self._models if model.__collection_name__() == key))
|
|
206
|
+
)
|
|
183
207
|
|
|
184
208
|
async def rollback(self) -> None:
|
|
185
209
|
await self._connection.rollback()
|
|
@@ -196,9 +220,9 @@ class SQLiteConnection(ConnectionProtocol):
|
|
|
196
220
|
return [row[0] for row in rows]
|
|
197
221
|
|
|
198
222
|
async def create(self, model: Model, *, exists_ok=False) -> None:
|
|
199
|
-
model._update_meta(
|
|
223
|
+
model._update_meta()
|
|
200
224
|
fields = []
|
|
201
|
-
for field_name in model.__dict__
|
|
225
|
+
for field_name in model.__dict__:
|
|
202
226
|
field = getattr(model, field_name)
|
|
203
227
|
if field_name.startswith('_') or not isinstance(field, Field):
|
|
204
228
|
continue
|
|
@@ -210,7 +234,8 @@ class SQLiteConnection(ConnectionProtocol):
|
|
|
210
234
|
{'UNIQUE' if hasattr(field, 'unique') and field.unique else ''}
|
|
211
235
|
{'NOT NULL' if (hasattr(field, 'not_null') and field.not_null) or field_name not in model._meta_primary_keys else ''}
|
|
212
236
|
{f'REFERENCES {field.reference.collection_name}({field.reference.field_name})'
|
|
213
|
-
|
|
237
|
+
if hasattr(field, 'reference') and field.reference else ''}
|
|
238
|
+
{f'DEFAULT {field.default_expr}' if hasattr(field, 'default_expr') else ''}
|
|
214
239
|
'''.strip()
|
|
215
240
|
)
|
|
216
241
|
await self._fetch(f'''
|
|
@@ -219,6 +244,7 @@ class SQLiteConnection(ConnectionProtocol):
|
|
|
219
244
|
{f',PRIMARY KEY ({','.join(model._meta_primary_keys)})' if len(model._meta_primary_keys) > 1 else ''}
|
|
220
245
|
);
|
|
221
246
|
'''.strip())
|
|
247
|
+
self._models.add(model)
|
|
222
248
|
|
|
223
249
|
async def create_index(
|
|
224
250
|
self,
|
|
@@ -250,7 +276,7 @@ class SQLiteConnection(ConnectionProtocol):
|
|
|
250
276
|
finally:
|
|
251
277
|
await self._pool.release(self)
|
|
252
278
|
|
|
253
|
-
async def _fetch(self, query: str, *args, timeout:
|
|
279
|
+
async def _fetch(self, query: str, *args, timeout: float | None = None) -> list:
|
|
254
280
|
async with asyncio.timeout(timeout):
|
|
255
281
|
query = " ".join(line.strip() for line in query.split("\n")).strip()
|
|
256
282
|
async with self._connection.execute(query, args) as cursor:
|
|
@@ -258,7 +284,21 @@ class SQLiteConnection(ConnectionProtocol):
|
|
|
258
284
|
|
|
259
285
|
async def _execute(self, query: str, *args) -> None:
|
|
260
286
|
query = " ".join(line.strip() for line in query.split("\n")).strip()
|
|
261
|
-
|
|
287
|
+
async with self._connection.execute(query, args):
|
|
288
|
+
pass
|
|
289
|
+
|
|
290
|
+
async def _executemany(
|
|
291
|
+
self,
|
|
292
|
+
query: str,
|
|
293
|
+
params_seq: Iterable[Sequence[Any]],
|
|
294
|
+
*,
|
|
295
|
+
timeout: float | None = None,
|
|
296
|
+
) -> int:
|
|
297
|
+
query = " ".join(line.strip() for line in query.split("\n")).strip()
|
|
298
|
+
async with asyncio.timeout(timeout):
|
|
299
|
+
async with self._connection.cursor() as cursor:
|
|
300
|
+
await cursor.executemany(query, params_seq)
|
|
301
|
+
return cursor.rowcount
|
|
262
302
|
|
|
263
303
|
|
|
264
304
|
class SQLitePool(PoolProtocol):
|
|
@@ -316,9 +356,9 @@ class SQLitePool(PoolProtocol):
|
|
|
316
356
|
|
|
317
357
|
|
|
318
358
|
def SQLite(
|
|
319
|
-
dsn:
|
|
359
|
+
dsn: str | None = None,
|
|
320
360
|
*,
|
|
321
|
-
database:
|
|
361
|
+
database: str | None = None,
|
|
322
362
|
autocommit: bool = True,
|
|
323
363
|
**kwargs,
|
|
324
364
|
) -> SQLitePool:
|
|
@@ -331,5 +371,5 @@ def SQLite(
|
|
|
331
371
|
:return: SQLitePool instance
|
|
332
372
|
"""
|
|
333
373
|
if dsn:
|
|
334
|
-
return SQLitePool(dsn.split(':')[1], autocommit=autocommit, **kwargs)
|
|
374
|
+
return SQLitePool(dsn.split(':')[1].removeprefix('//'), autocommit=autocommit, **kwargs)
|
|
335
375
|
return SQLitePool(database, autocommit=autocommit, **kwargs)
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "slinn-orm"
|
|
7
|
-
version = "0.0.
|
|
7
|
+
version = "0.0.5"
|
|
8
8
|
description = "ORM for Slinn"
|
|
9
9
|
requires-python = ">=3.14"
|
|
10
10
|
authors = [{ name = "Mark Radin", email = "openmiot@gmail.com" }]
|
|
@@ -17,7 +17,3 @@ full = ["slinn-orm[postgres]", "slinn-orm[sqlite]"]
|
|
|
17
17
|
[tool.setuptools.packages.find]
|
|
18
18
|
where = ["."]
|
|
19
19
|
include = ["orm*"]
|
|
20
|
-
|
|
21
|
-
[tool.uv]
|
|
22
|
-
managed = true
|
|
23
|
-
workspace = { }
|
slinn_orm-0.0.3/orm/models.py
DELETED
|
@@ -1,97 +0,0 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
|
-
from abc import ABC, abstractmethod
|
|
3
|
-
from typing import Literal, Optional
|
|
4
|
-
from datetime import timedelta, datetime
|
|
5
|
-
from typing import NamedTuple
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
class Model(ABC):
|
|
9
|
-
@staticmethod
|
|
10
|
-
@abstractmethod
|
|
11
|
-
def __collection_name__() -> str: ...
|
|
12
|
-
|
|
13
|
-
def _update_meta(self) -> None:
|
|
14
|
-
if not hasattr(self, '_meta_primary_keys'):
|
|
15
|
-
self._meta_primary_keys = ()
|
|
16
|
-
|
|
17
|
-
for field_name in self.__dict__.keys():
|
|
18
|
-
field = self.__dict__[field_name]
|
|
19
|
-
if field_name.startswith('_') or not isinstance(field, Field):
|
|
20
|
-
continue
|
|
21
|
-
if hasattr(field, 'primary') and field.primary:
|
|
22
|
-
if field_name not in self._meta_primary_keys:
|
|
23
|
-
self._meta_primary_keys = (*self._meta_primary_keys, field_name)
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
class Field(ABC):
|
|
27
|
-
class FieldReference(NamedTuple):
|
|
28
|
-
collection_name: str
|
|
29
|
-
field_name: str
|
|
30
|
-
|
|
31
|
-
def make_identity(self) -> Field:
|
|
32
|
-
self.identity = True
|
|
33
|
-
return self
|
|
34
|
-
|
|
35
|
-
def make_primary(self) -> Field:
|
|
36
|
-
self.primary = True
|
|
37
|
-
return self
|
|
38
|
-
|
|
39
|
-
def make_unique(self) -> Field:
|
|
40
|
-
self.unique = True
|
|
41
|
-
return self
|
|
42
|
-
|
|
43
|
-
def make_not_null(self) -> Field:
|
|
44
|
-
self.not_null = True
|
|
45
|
-
return self
|
|
46
|
-
|
|
47
|
-
def set_reference(self, collection_name: str, field_name: str) -> Field:
|
|
48
|
-
self.reference = self.FieldReference(collection_name, field_name)
|
|
49
|
-
return self
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
class BoolField(Field): ...
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
class IntegerField(Field):
|
|
56
|
-
def __init__(self, *, size: Literal[2, 4, 8] = 4):
|
|
57
|
-
self.size = size
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
class DecimalField(Field): ...
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
class FloatField(Field):
|
|
64
|
-
def __init__(self, *, double: bool = False):
|
|
65
|
-
self.double = double
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
class TextField(Field): ...
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
class TimeField(Field):
|
|
72
|
-
def __init__(
|
|
73
|
-
self,
|
|
74
|
-
*,
|
|
75
|
-
zone: bool = True,
|
|
76
|
-
date: bool = True,
|
|
77
|
-
time: bool = True,
|
|
78
|
-
default: Optional[timedelta | datetime]
|
|
79
|
-
):
|
|
80
|
-
self.zone = zone
|
|
81
|
-
self.date = date
|
|
82
|
-
self.time = time
|
|
83
|
-
self.default = default
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
class TimeDeltaField(Field): ...
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
class BinaryField(Field): ...
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
class UIDField(Field):
|
|
93
|
-
def __init__(self):
|
|
94
|
-
self.make_identity()
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
class UUIDField(Field): ...
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|