slinn-orm 0.0.3__tar.gz → 0.0.4__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {slinn_orm-0.0.3/slinn_orm.egg-info → slinn_orm-0.0.4}/PKG-INFO +1 -1
- slinn_orm-0.0.4/orm/models.py +162 -0
- {slinn_orm-0.0.3 → slinn_orm-0.0.4}/orm/postgres/__init__.py +25 -14
- {slinn_orm-0.0.3 → slinn_orm-0.0.4}/orm/sqlite/__init__.py +36 -23
- {slinn_orm-0.0.3 → slinn_orm-0.0.4}/pyproject.toml +1 -5
- {slinn_orm-0.0.3 → slinn_orm-0.0.4/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.4}/LICENSE +0 -0
- {slinn_orm-0.0.3 → slinn_orm-0.0.4}/orm/__init__.py +0 -0
- {slinn_orm-0.0.3 → slinn_orm-0.0.4}/orm/attributed_dict.py +0 -0
- {slinn_orm-0.0.3 → slinn_orm-0.0.4}/orm/order.py +0 -0
- {slinn_orm-0.0.3 → slinn_orm-0.0.4}/orm/typemap.py +0 -0
- {slinn_orm-0.0.3 → slinn_orm-0.0.4}/setup.cfg +0 -0
- {slinn_orm-0.0.3 → slinn_orm-0.0.4}/slinn_orm.egg-info/SOURCES.txt +0 -0
- {slinn_orm-0.0.3 → slinn_orm-0.0.4}/slinn_orm.egg-info/dependency_links.txt +0 -0
- {slinn_orm-0.0.3 → slinn_orm-0.0.4}/slinn_orm.egg-info/requires.txt +0 -0
- {slinn_orm-0.0.3 → slinn_orm-0.0.4}/slinn_orm.egg-info/top_level.txt +0 -0
|
@@ -0,0 +1,162 @@
|
|
|
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
|
+
|
|
50
|
+
class Field(ABC):
|
|
51
|
+
class FieldReference(NamedTuple):
|
|
52
|
+
collection_name: str
|
|
53
|
+
field_name: str
|
|
54
|
+
|
|
55
|
+
def __serialize__(self, value: Any) -> Any:
|
|
56
|
+
return value
|
|
57
|
+
|
|
58
|
+
def __deserialize__(self, value: Any) -> Any:
|
|
59
|
+
return value
|
|
60
|
+
|
|
61
|
+
def make_identity(self) -> Field:
|
|
62
|
+
self.identity = True
|
|
63
|
+
return self
|
|
64
|
+
|
|
65
|
+
def make_primary(self) -> Field:
|
|
66
|
+
self.primary = True
|
|
67
|
+
return self
|
|
68
|
+
|
|
69
|
+
def make_unique(self) -> Field:
|
|
70
|
+
self.unique = True
|
|
71
|
+
return self
|
|
72
|
+
|
|
73
|
+
def make_not_null(self) -> Field:
|
|
74
|
+
self.not_null = True
|
|
75
|
+
return self
|
|
76
|
+
|
|
77
|
+
def set_reference(self, collection_name: str, field_name: str) -> Field:
|
|
78
|
+
self.reference = self.FieldReference(collection_name, field_name)
|
|
79
|
+
return self
|
|
80
|
+
|
|
81
|
+
def set_default_expr(self, default_expr: str) -> Field:
|
|
82
|
+
self.default_expr = default_expr
|
|
83
|
+
return self
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class BoolField(Field): ...
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class IntegerField(Field):
|
|
90
|
+
def __init__(self, *, size: Literal[2, 4, 8] = 4):
|
|
91
|
+
self.size = size
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class DecimalField(Field): ...
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class FloatField(Field):
|
|
98
|
+
def __init__(self, *, double: bool = False):
|
|
99
|
+
self.double = double
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class TextField(Field): ...
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class TimeField(Field):
|
|
106
|
+
def __init__(
|
|
107
|
+
self,
|
|
108
|
+
*,
|
|
109
|
+
zone: bool = True,
|
|
110
|
+
date: bool = True,
|
|
111
|
+
time: bool = True,
|
|
112
|
+
default: timedelta | datetime | None
|
|
113
|
+
):
|
|
114
|
+
self.zone = zone
|
|
115
|
+
self.date = date
|
|
116
|
+
self.time = time
|
|
117
|
+
self.default = default
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class TimeDeltaField(Field): ...
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class BinaryField(Field): ...
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class UIDField(Field):
|
|
127
|
+
def __init__(self):
|
|
128
|
+
self.make_identity()
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class UUIDField(Field):
|
|
132
|
+
def __init__(self):
|
|
133
|
+
self.set_default_expr("""
|
|
134
|
+
(
|
|
135
|
+
unhex(
|
|
136
|
+
hex(
|
|
137
|
+
unhex(
|
|
138
|
+
substr(
|
|
139
|
+
hex(zeroblob(8) || printf('%016X', CAST(unixepoch('subsecond') * 1000 AS INTEGER))), -12
|
|
140
|
+
)
|
|
141
|
+
)
|
|
142
|
+
)
|
|
143
|
+
||
|
|
144
|
+
'7' || substr(hex(randomblob(2)), 2, 3)
|
|
145
|
+
||
|
|
146
|
+
substr('89AB', 1 + (abs(random()) % 4), 1) || substr(hex(randomblob(8)), 2)
|
|
147
|
+
)
|
|
148
|
+
)
|
|
149
|
+
""")
|
|
150
|
+
|
|
151
|
+
class InetField(Field):
|
|
152
|
+
def __serialize__(self, ip: IPv4Address | IPv6Address | str | int) -> bytes:
|
|
153
|
+
if isinstance(ip, str):
|
|
154
|
+
ip = ip_address(ip)
|
|
155
|
+
return ip.packed
|
|
156
|
+
|
|
157
|
+
def __deserialize__(self, ip: IPv4Address | IPv6Address | str | int | bytes) -> IPv4Address | IPv6Address:
|
|
158
|
+
if isinstance(ip, (IPv4Address, IPv6Address)):
|
|
159
|
+
return ip
|
|
160
|
+
if isinstance(ip, (str, int, bytes)):
|
|
161
|
+
return ip_address(ip)
|
|
162
|
+
|
|
@@ -3,8 +3,10 @@ from .. import CollectionProtocol, ConnectionProtocol, PoolProtocol
|
|
|
3
3
|
from ..attributed_dict import AttributedDict
|
|
4
4
|
from ..typemap import typemap as tm
|
|
5
5
|
from ..order import OrderType
|
|
6
|
-
from ..models import (
|
|
7
|
-
|
|
6
|
+
from ..models import (
|
|
7
|
+
Model, Field, BoolField, IntegerField, DecimalField, FloatField, TextField, TimeField, TimeDeltaField,
|
|
8
|
+
BinaryField, UIDField, UUIDField, InetField
|
|
9
|
+
)
|
|
8
10
|
from typing import Coroutine, Optional, Final
|
|
9
11
|
from functools import partial
|
|
10
12
|
from datetime import datetime, timedelta
|
|
@@ -12,9 +14,10 @@ import asyncpg
|
|
|
12
14
|
|
|
13
15
|
|
|
14
16
|
class PostgresCollection(CollectionProtocol):
|
|
15
|
-
def __init__(self, connection: PostgresConnection, name: str):
|
|
17
|
+
def __init__(self, connection: PostgresConnection, name: str, model: Model | None = None):
|
|
16
18
|
self.connection = connection
|
|
17
19
|
self.name = name
|
|
20
|
+
self.model = model
|
|
18
21
|
|
|
19
22
|
async def find(
|
|
20
23
|
self,
|
|
@@ -22,7 +25,7 @@ class PostgresCollection(CollectionProtocol):
|
|
|
22
25
|
*,
|
|
23
26
|
fields: tuple[str] = ('*',),
|
|
24
27
|
order: tuple[tuple[OrderType, str]] = ()) -> list[dict]:
|
|
25
|
-
return [
|
|
28
|
+
return [self.model.__deserialize_object__(record) for record in await self.connection._fetch(
|
|
26
29
|
f'SELECT {', '.join(fields)} '
|
|
27
30
|
f'FROM {self.name} '
|
|
28
31
|
f'{'WHERE ' if _filter else ''}{' AND '.join([f'{list(_filter.keys())[i]}=${i+1}' for i in range(0, len(_filter))])} '
|
|
@@ -48,9 +51,11 @@ class PostgresCollection(CollectionProtocol):
|
|
|
48
51
|
typemap: dict | None = None) -> None:
|
|
49
52
|
if not _object:
|
|
50
53
|
return []
|
|
54
|
+
if self.model:
|
|
55
|
+
_object = self.model.__serialize_object__(_object)
|
|
51
56
|
records = await self.connection._fetch(
|
|
52
57
|
f'INSERT INTO {self.name}({', '.join(_object.keys())}) '
|
|
53
|
-
f'VALUES({', '.join([f'${i+1}' for i in range(
|
|
58
|
+
f'VALUES({', '.join([f'${i+1}' for i in range(len(_object))])}) '
|
|
54
59
|
f'{'RETURNING' if returning else ''} {', '.join(returning)}',
|
|
55
60
|
*tm(_object, typemap).values())
|
|
56
61
|
return records[0] if records else None
|
|
@@ -64,6 +69,8 @@ class PostgresCollection(CollectionProtocol):
|
|
|
64
69
|
typemap: dict | None = None) -> None:
|
|
65
70
|
if not _object:
|
|
66
71
|
return []
|
|
72
|
+
if self.model:
|
|
73
|
+
_object = self.model.__serialize_object__(_object)
|
|
67
74
|
return await self.connection._fetch(
|
|
68
75
|
f'UPDATE {self.name} '
|
|
69
76
|
f'SET {', '.join([f'{key}=${i+1}' for i, key in enumerate(_object)])} '
|
|
@@ -94,6 +101,7 @@ class PostgresCollection(CollectionProtocol):
|
|
|
94
101
|
FROM {self.name}
|
|
95
102
|
{'WHERE ' if _filter else ''}{' AND '.join([f'{list(_filter.keys())[i]}=${i+1}' for i in range(0, len(_filter))])};''',
|
|
96
103
|
*_filter.values()))[0]['count']
|
|
104
|
+
|
|
97
105
|
async def get_size(self) -> int: ...
|
|
98
106
|
|
|
99
107
|
async def drop(self, *, not_exists_ok: bool = False) -> None:
|
|
@@ -127,18 +135,22 @@ class PostgresConnection(ConnectionProtocol):
|
|
|
127
135
|
TimeDeltaField: lambda field: 'INTERVAL',
|
|
128
136
|
BinaryField: lambda field: 'BYTEA',
|
|
129
137
|
UIDField: lambda field: 'BIGINT',
|
|
130
|
-
UUIDField: lambda field: 'UUID'
|
|
138
|
+
UUIDField: lambda field: 'UUID',
|
|
139
|
+
InetField: lambda field: 'INET'
|
|
131
140
|
}
|
|
132
141
|
|
|
133
|
-
def __init__(self, pool, connection, transaction, autocommit=True):
|
|
142
|
+
def __init__(self, pool, connection, transaction, autocommit: bool = True):
|
|
134
143
|
self._pool = pool
|
|
135
144
|
self._connection = connection
|
|
136
145
|
self._transaction = transaction
|
|
137
146
|
self._autocommit = autocommit
|
|
147
|
+
self._models = set()
|
|
138
148
|
self.collection = self.__getattr__
|
|
139
149
|
|
|
140
150
|
def __getattr__(self, key) -> CollectionProtocol:
|
|
141
|
-
return PostgresCollection(
|
|
151
|
+
return PostgresCollection(
|
|
152
|
+
self, key, model = next(iter(model for model in self._models if model.__collection_name__() == key))
|
|
153
|
+
)
|
|
142
154
|
|
|
143
155
|
async def rollback(self) -> None:
|
|
144
156
|
await self._transaction.rollback()
|
|
@@ -154,9 +166,9 @@ class PostgresConnection(ConnectionProtocol):
|
|
|
154
166
|
ORDER BY table_name;''')]
|
|
155
167
|
|
|
156
168
|
async def create(self, model: Model, *, exists_ok=False) -> None:
|
|
157
|
-
model._update_meta(
|
|
169
|
+
model._update_meta()
|
|
158
170
|
fields = []
|
|
159
|
-
for field_name in model.__dict__
|
|
171
|
+
for field_name in model.__dict__:
|
|
160
172
|
field = getattr(model, field_name)
|
|
161
173
|
if field_name.startswith('_') or not isinstance(field, Field):
|
|
162
174
|
continue
|
|
@@ -167,7 +179,8 @@ class PostgresConnection(ConnectionProtocol):
|
|
|
167
179
|
{'NOT NULL' if hasattr(field, 'not_null') and field.not_null else ''}
|
|
168
180
|
{'GENERATED ALWAYS AS IDENTITY' if hasattr(field, 'identity') and field.identity else ''}
|
|
169
181
|
{f'REFERENCES {field.reference.collection_name}({field.reference.field_name})'
|
|
170
|
-
|
|
182
|
+
if hasattr(field, 'reference') and field.reference else ''}
|
|
183
|
+
{f'DEFAULT {field.default_expr}' if hasattr(field, 'default_expr') else ''}
|
|
171
184
|
'''.strip()
|
|
172
185
|
)
|
|
173
186
|
await self._fetch(f'''
|
|
@@ -176,6 +189,7 @@ class PostgresConnection(ConnectionProtocol):
|
|
|
176
189
|
{f'PRIMARY KEY ({','.join(model._meta_primary_keys)})' if model._meta_primary_keys else ''}
|
|
177
190
|
);
|
|
178
191
|
'''.strip())
|
|
192
|
+
self._models.add(model)
|
|
179
193
|
|
|
180
194
|
async def create_index(
|
|
181
195
|
self,
|
|
@@ -186,9 +200,6 @@ class PostgresConnection(ConnectionProtocol):
|
|
|
186
200
|
exists_ok: bool=False,
|
|
187
201
|
unique: bool=False
|
|
188
202
|
) -> 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
203
|
await self._fetch(f'''
|
|
193
204
|
CREATE {'UNIQUE ' if unique else ''}INDEX {'IF NOT EXISTS ' if exists_ok else ''}{index_name} ON {collection_name}({','.join(fields)});
|
|
194
205
|
''')
|
|
@@ -5,17 +5,20 @@ from .. import CollectionProtocol, ConnectionProtocol, PoolProtocol
|
|
|
5
5
|
from ..attributed_dict import AttributedDict
|
|
6
6
|
from ..typemap import typemap as tm
|
|
7
7
|
from ..order import OrderType
|
|
8
|
-
from ..models import (
|
|
9
|
-
|
|
8
|
+
from ..models import (
|
|
9
|
+
Model, Field, BoolField, IntegerField, DecimalField, FloatField, TextField, TimeField, TimeDeltaField,
|
|
10
|
+
BinaryField, UIDField, UUIDField, InetField
|
|
11
|
+
)
|
|
10
12
|
from datetime import datetime, timedelta
|
|
11
13
|
import aiosqlite
|
|
12
14
|
import asyncio
|
|
13
15
|
|
|
14
16
|
|
|
15
17
|
class SQLiteCollection(CollectionProtocol):
|
|
16
|
-
def __init__(self, connection: SQLiteConnection, name: str):
|
|
18
|
+
def __init__(self, connection: SQLiteConnection, name: str, model: Model | None = None):
|
|
17
19
|
self.connection = connection
|
|
18
20
|
self.name = name
|
|
21
|
+
self.model = model
|
|
19
22
|
|
|
20
23
|
async def find(
|
|
21
24
|
self,
|
|
@@ -27,7 +30,7 @@ class SQLiteCollection(CollectionProtocol):
|
|
|
27
30
|
where_clause = ""
|
|
28
31
|
params = []
|
|
29
32
|
if _filter:
|
|
30
|
-
conditions = [f"{key} = ?" for key in _filter
|
|
33
|
+
conditions = [f"{key} = ?" for key in _filter]
|
|
31
34
|
where_clause = f"WHERE {' AND '.join(conditions)}"
|
|
32
35
|
params.extend(_filter.values())
|
|
33
36
|
|
|
@@ -41,11 +44,11 @@ class SQLiteCollection(CollectionProtocol):
|
|
|
41
44
|
|
|
42
45
|
query = f"SELECT {', '.join(fields)} FROM {self.name} {where_clause} {order_clause}"
|
|
43
46
|
rows = await self.connection._fetch(query, *params)
|
|
44
|
-
return [
|
|
47
|
+
return [self.model.__deserialize_object__(row) for row in rows]
|
|
45
48
|
|
|
46
49
|
async def find_one(
|
|
47
50
|
self, _filter: dict, *, fields: tuple[str] = ("*",)
|
|
48
|
-
) ->
|
|
51
|
+
) -> dict | None:
|
|
49
52
|
result = await self.find(_filter, fields=fields)
|
|
50
53
|
return result[0] if result else None
|
|
51
54
|
|
|
@@ -54,10 +57,12 @@ class SQLiteCollection(CollectionProtocol):
|
|
|
54
57
|
_object: dict,
|
|
55
58
|
*,
|
|
56
59
|
returning: tuple[str] = (),
|
|
57
|
-
typemap:
|
|
58
|
-
) ->
|
|
60
|
+
typemap: dict | None = None,
|
|
61
|
+
) -> dict | None:
|
|
59
62
|
if not _object:
|
|
60
63
|
return None
|
|
64
|
+
if self.model:
|
|
65
|
+
_object = self.model.__serialize_object__(_object)
|
|
61
66
|
|
|
62
67
|
data = tm(_object, typemap)
|
|
63
68
|
columns = ", ".join(data.keys())
|
|
@@ -76,18 +81,20 @@ class SQLiteCollection(CollectionProtocol):
|
|
|
76
81
|
_object: dict,
|
|
77
82
|
*,
|
|
78
83
|
returning: tuple[str] = (),
|
|
79
|
-
typemap:
|
|
84
|
+
typemap: dict | None = None,
|
|
80
85
|
) -> list[dict]:
|
|
81
86
|
if not _object:
|
|
82
87
|
return []
|
|
88
|
+
if self.model:
|
|
89
|
+
_object = self.model.__serialize_object__(_object)
|
|
83
90
|
|
|
84
91
|
data = tm(_object, typemap)
|
|
85
|
-
set_clause = ", ".join([f"{key} = ?" for key in data
|
|
92
|
+
set_clause = ", ".join([f"{key} = ?" for key in data])
|
|
86
93
|
params = list(data.values())
|
|
87
94
|
|
|
88
95
|
where_clause = ""
|
|
89
96
|
if _filter:
|
|
90
|
-
conditions = [f"{key} = ?" for key in _filter
|
|
97
|
+
conditions = [f"{key} = ?" for key in _filter]
|
|
91
98
|
where_clause = f"WHERE {' AND '.join(conditions)}"
|
|
92
99
|
params.extend(_filter.values())
|
|
93
100
|
|
|
@@ -102,7 +109,7 @@ class SQLiteCollection(CollectionProtocol):
|
|
|
102
109
|
where_clause = ""
|
|
103
110
|
params = []
|
|
104
111
|
if _filter:
|
|
105
|
-
conditions = [f"{key} = ?" for key in _filter
|
|
112
|
+
conditions = [f"{key} = ?" for key in _filter]
|
|
106
113
|
where_clause = f"WHERE {' AND '.join(conditions)}"
|
|
107
114
|
params.extend(_filter.values())
|
|
108
115
|
|
|
@@ -111,11 +118,11 @@ class SQLiteCollection(CollectionProtocol):
|
|
|
111
118
|
|
|
112
119
|
async def pop(
|
|
113
120
|
self, _filter: dict, *, returning: tuple[str] = ("*",)
|
|
114
|
-
) ->
|
|
121
|
+
) -> dict | None:
|
|
115
122
|
where_clause = ""
|
|
116
123
|
params = []
|
|
117
124
|
if _filter:
|
|
118
|
-
conditions = [f"{key} = ?" for key in _filter
|
|
125
|
+
conditions = [f"{key} = ?" for key in _filter]
|
|
119
126
|
where_clause = f"WHERE {' AND '.join(conditions)}"
|
|
120
127
|
params.extend(_filter.values())
|
|
121
128
|
|
|
@@ -128,7 +135,7 @@ class SQLiteCollection(CollectionProtocol):
|
|
|
128
135
|
where_clause = ""
|
|
129
136
|
params = []
|
|
130
137
|
if _filter:
|
|
131
|
-
conditions = [f"{key} = ?" for key in _filter
|
|
138
|
+
conditions = [f"{key} = ?" for key in _filter]
|
|
132
139
|
where_clause = f"WHERE {' AND '.join(conditions)}"
|
|
133
140
|
params.extend(_filter.values())
|
|
134
141
|
|
|
@@ -168,7 +175,8 @@ class SQLiteConnection(ConnectionProtocol):
|
|
|
168
175
|
TimeDeltaField: lambda field: 'INTEGER',
|
|
169
176
|
BinaryField: lambda field: 'BLOB',
|
|
170
177
|
UIDField: lambda field: 'INTEGER',
|
|
171
|
-
UUIDField: lambda field: 'TEXT'
|
|
178
|
+
UUIDField: lambda field: 'TEXT',
|
|
179
|
+
InetField: lambda field: 'BLOB'
|
|
172
180
|
}
|
|
173
181
|
|
|
174
182
|
def __init__(self, pool: SQLitePool, connection: aiosqlite.Connection, autocommit: bool = True):
|
|
@@ -176,10 +184,13 @@ class SQLiteConnection(ConnectionProtocol):
|
|
|
176
184
|
self._connection = connection
|
|
177
185
|
self._autocommit = autocommit
|
|
178
186
|
self._in_transaction = False
|
|
187
|
+
self._models = set()
|
|
179
188
|
self.collection = self.__getattr__
|
|
180
189
|
|
|
181
190
|
def __getattr__(self, key) -> CollectionProtocol:
|
|
182
|
-
return SQLiteCollection(
|
|
191
|
+
return SQLiteCollection(
|
|
192
|
+
self, key, model = next(iter(model for model in self._models if model.__collection_name__() == key))
|
|
193
|
+
)
|
|
183
194
|
|
|
184
195
|
async def rollback(self) -> None:
|
|
185
196
|
await self._connection.rollback()
|
|
@@ -196,9 +207,9 @@ class SQLiteConnection(ConnectionProtocol):
|
|
|
196
207
|
return [row[0] for row in rows]
|
|
197
208
|
|
|
198
209
|
async def create(self, model: Model, *, exists_ok=False) -> None:
|
|
199
|
-
model._update_meta(
|
|
210
|
+
model._update_meta()
|
|
200
211
|
fields = []
|
|
201
|
-
for field_name in model.__dict__
|
|
212
|
+
for field_name in model.__dict__:
|
|
202
213
|
field = getattr(model, field_name)
|
|
203
214
|
if field_name.startswith('_') or not isinstance(field, Field):
|
|
204
215
|
continue
|
|
@@ -210,7 +221,8 @@ class SQLiteConnection(ConnectionProtocol):
|
|
|
210
221
|
{'UNIQUE' if hasattr(field, 'unique') and field.unique else ''}
|
|
211
222
|
{'NOT NULL' if (hasattr(field, 'not_null') and field.not_null) or field_name not in model._meta_primary_keys else ''}
|
|
212
223
|
{f'REFERENCES {field.reference.collection_name}({field.reference.field_name})'
|
|
213
|
-
|
|
224
|
+
if hasattr(field, 'reference') and field.reference else ''}
|
|
225
|
+
{f'DEFAULT {field.default_expr}' if hasattr(field, 'default_expr') else ''}
|
|
214
226
|
'''.strip()
|
|
215
227
|
)
|
|
216
228
|
await self._fetch(f'''
|
|
@@ -219,6 +231,7 @@ class SQLiteConnection(ConnectionProtocol):
|
|
|
219
231
|
{f',PRIMARY KEY ({','.join(model._meta_primary_keys)})' if len(model._meta_primary_keys) > 1 else ''}
|
|
220
232
|
);
|
|
221
233
|
'''.strip())
|
|
234
|
+
self._models.add(model)
|
|
222
235
|
|
|
223
236
|
async def create_index(
|
|
224
237
|
self,
|
|
@@ -316,9 +329,9 @@ class SQLitePool(PoolProtocol):
|
|
|
316
329
|
|
|
317
330
|
|
|
318
331
|
def SQLite(
|
|
319
|
-
dsn:
|
|
332
|
+
dsn: str | None = None,
|
|
320
333
|
*,
|
|
321
|
-
database:
|
|
334
|
+
database: str | None = None,
|
|
322
335
|
autocommit: bool = True,
|
|
323
336
|
**kwargs,
|
|
324
337
|
) -> SQLitePool:
|
|
@@ -331,5 +344,5 @@ def SQLite(
|
|
|
331
344
|
:return: SQLitePool instance
|
|
332
345
|
"""
|
|
333
346
|
if dsn:
|
|
334
|
-
return SQLitePool(dsn.split(':')[1], autocommit=autocommit, **kwargs)
|
|
347
|
+
return SQLitePool(dsn.split(':')[1].removeprefix('//'), autocommit=autocommit, **kwargs)
|
|
335
348
|
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.4"
|
|
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
|
|
File without changes
|