slinn-orm 0.0.4__tar.gz → 0.0.6__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: slinn-orm
3
- Version: 0.0.4
3
+ Version: 0.0.6
4
4
  Summary: ORM for Slinn
5
5
  Author-email: Mark Radin <openmiot@gmail.com>
6
6
  Requires-Python: >=3.14
@@ -1,5 +1,4 @@
1
- from __future__ import annotations
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) -> ConnectionProtocol: ...
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: ...
@@ -48,3 +48,13 @@ class PoolProtocol(Protocol):
48
48
 
49
49
  def get_driver_name(dsn: str) -> str:
50
50
  return DSN_PATTERN.findall(dsn)[0][0].lower()
51
+
52
+
53
+ def get_pool(dsn: str) -> PoolProtocol:
54
+ match get_driver_name(dsn):
55
+ case 'sqlite' | 'sqlite3':
56
+ from orm.sqlite import SQLite
57
+ return SQLite(dsn)
58
+ case 'postgres' | 'pg':
59
+ from orm.postgres import Postgres
60
+ return Postgres(dsn)
@@ -3,6 +3,7 @@ from typing import Literal, Optional
3
3
  from datetime import timedelta, datetime
4
4
  from typing import NamedTuple, Any
5
5
  from ipaddress import IPv4Address, IPv6Address, ip_address
6
+ import enum
6
7
 
7
8
 
8
9
  class Model(ABC):
@@ -45,6 +46,11 @@ class Model(ABC):
45
46
  continue
46
47
  result[field_name] = field.__deserialize__(obj[field_name])
47
48
  return result
49
+
50
+ def __new__(cls, **kwargs):
51
+ if kwargs:
52
+ return cls().__serialize_object__(kwargs)
53
+ return object.__new__(cls)
48
54
 
49
55
 
50
56
  class Field(ABC):
@@ -89,6 +95,11 @@ class BoolField(Field): ...
89
95
  class IntegerField(Field):
90
96
  def __init__(self, *, size: Literal[2, 4, 8] = 4):
91
97
  self.size = size
98
+
99
+ def __serialize__(self, value: Any) -> int:
100
+ if isinstance(value, enum.Enum):
101
+ return value.value
102
+ return int(value)
92
103
 
93
104
 
94
105
  class DecimalField(Field): ...
@@ -99,7 +110,11 @@ class FloatField(Field):
99
110
  self.double = double
100
111
 
101
112
 
102
- class TextField(Field): ...
113
+ class TextField(Field):
114
+ def __serialize__(self, value: Any) -> str:
115
+ if isinstance(value, enum.Enum):
116
+ return value.name
117
+ return str(value)
103
118
 
104
119
 
105
120
  class TimeField(Field):
@@ -1,16 +1,15 @@
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
4
  from ..models import (
7
5
  Model, Field, BoolField, IntegerField, DecimalField, FloatField, TextField, TimeField, TimeDeltaField,
8
6
  BinaryField, UIDField, UUIDField, InetField
9
7
  )
10
- from typing import Coroutine, Optional, Final
8
+ from typing import Coroutine, Optional, Final, Iterable, Sequence, Any
11
9
  from functools import partial
12
10
  from datetime import datetime, timedelta
13
11
  import asyncpg
12
+ import asyncio
14
13
 
15
14
 
16
15
  class PostgresCollection(CollectionProtocol):
@@ -59,6 +58,23 @@ class PostgresCollection(CollectionProtocol):
59
58
  f'{'RETURNING' if returning else ''} {', '.join(returning)}',
60
59
  *tm(_object, typemap).values())
61
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
+
62
78
 
63
79
  async def update(
64
80
  self,
@@ -225,6 +241,17 @@ class PostgresConnection(ConnectionProtocol):
225
241
  timeout=timeout,
226
242
  record_class=record_class
227
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)
228
255
 
229
256
  class PostgresPool(PoolProtocol):
230
257
  def __init__(self, pool_factory, autocommit=True):
@@ -256,28 +283,28 @@ class PostgresPool(PoolProtocol):
256
283
 
257
284
 
258
285
  def Postgres(
259
- dsn: Optional[str] = None,
286
+ dsn: str | None = None,
260
287
  *,
261
- host: Optional[str] = None,
262
- port: Optional[int] = None,
263
- user: Optional[str] = None,
264
- password: Optional[str] = None,
265
- database: Optional[str] = None,
266
- server_settings: Optional[dict] = None,
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,
267
294
  autocommit: bool = True) -> PostgresPool:
268
295
  return PostgresPool(
269
296
  partial(
270
297
  asyncpg.create_pool,
271
298
  dsn,
272
- server_settings=server_settings
299
+ server_settings = server_settings
273
300
  ) if dsn else partial(
274
301
  asyncpg.create_pool,
275
- host=host,
276
- port=port,
277
- user=user,
278
- password=password,
279
- database=database,
280
- server_settings=server_settings
302
+ host = host,
303
+ port = port,
304
+ user = user,
305
+ password = password,
306
+ database = database,
307
+ server_settings = server_settings
281
308
  ),
282
- autocommit=autocommit
309
+ autocommit = autocommit
283
310
  )
@@ -1,8 +1,5 @@
1
- from __future__ import annotations
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
5
  from ..models import (
@@ -75,6 +72,22 @@ class SQLiteCollection(CollectionProtocol):
75
72
  rows = await self.connection._fetch(query, *data.values())
76
73
  return rows[0] if rows else None
77
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
+
78
91
  async def update(
79
92
  self,
80
93
  _filter: dict,
@@ -263,7 +276,7 @@ class SQLiteConnection(ConnectionProtocol):
263
276
  finally:
264
277
  await self._pool.release(self)
265
278
 
266
- async def _fetch(self, query: str, *args, timeout: Optional[float] = None) -> list:
279
+ async def _fetch(self, query: str, *args, timeout: float | None = None) -> list:
267
280
  async with asyncio.timeout(timeout):
268
281
  query = " ".join(line.strip() for line in query.split("\n")).strip()
269
282
  async with self._connection.execute(query, args) as cursor:
@@ -271,7 +284,21 @@ class SQLiteConnection(ConnectionProtocol):
271
284
 
272
285
  async def _execute(self, query: str, *args) -> None:
273
286
  query = " ".join(line.strip() for line in query.split("\n")).strip()
274
- await self._connection.execute(query, args)
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
275
302
 
276
303
 
277
304
  class SQLitePool(PoolProtocol):
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "slinn-orm"
7
- version = "0.0.4"
7
+ version = "0.0.6"
8
8
  description = "ORM for Slinn"
9
9
  requires-python = ">=3.14"
10
10
  authors = [{ name = "Mark Radin", email = "openmiot@gmail.com" }]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: slinn-orm
3
- Version: 0.0.4
3
+ Version: 0.0.6
4
4
  Summary: ORM for Slinn
5
5
  Author-email: Mark Radin <openmiot@gmail.com>
6
6
  Requires-Python: >=3.14
File without changes
File without changes
File without changes
File without changes