-
Notifications
You must be signed in to change notification settings - Fork 0
/
_orm.py
817 lines (683 loc) · 26.8 KB
/
_orm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
from __future__ import annotations
import asyncio
import atexit
import logging
import queue
import sqlite3
import sys
import threading
from concurrent.futures import Future, ThreadPoolExecutor
from functools import cached_property
from typing import (
TYPE_CHECKING,
Any,
AsyncGenerator,
Callable,
Generator,
Generic,
Iterable,
Literal,
TypeVar,
overload,
)
from weakref import WeakValueDictionary
from typing_extensions import ParamSpec, deprecated
from simple_sqlite3_orm._sqlite_spec import INSERT_OR, ORDER_DIRECTION
from simple_sqlite3_orm._table_spec import TableSpec, TableSpecType
_parameterized_orm_cache: WeakValueDictionary[
tuple[type[ORMBase], type[TableSpec]], type[ORMBase[Any]]
] = WeakValueDictionary()
logger = logging.getLogger(__name__)
P = ParamSpec("P")
RT = TypeVar("RT")
if sys.version_info >= (3, 9):
from types import GenericAlias as _GenericAlias
else:
from typing import List
if not TYPE_CHECKING:
_GenericAlias = type(List[int])
else:
class _GenericAlias(type(List)):
def __new__(
cls, _type: type[Any], _params: type[Any] | tuple[type[Any], ...]
):
"""For type check only, typing the _GenericAlias as GenericAlias."""
class ORMBase(Generic[TableSpecType]):
"""ORM layer for <TableSpecType>.
NOTE that ORMBase will set the connection scope row_factory to <tablespec>'s table_row_factory.
See TableSpec.table_row_factory for more details.
NOTE that instance of ORMBase cannot be used in multi-threaded environment as the underlying
sqlite3 connection. Use ORMThreadPoolBase for multi-threaded environment. For asyncio,
use AsyncORMThreadPoolBase.
The underlying connection can be used in multiple connection for accessing different table in
the connected database.
Attributes:
con (sqlite3.Connection): The sqlite3 connection used by this ORM.
table_name (str): The name of the table in the database <con> connected to.
schema_name (str): the schema of the table if multiple databases are attached to <con>.
"""
orm_table_spec: type[TableSpecType]
def __init__(
self,
con: sqlite3.Connection,
table_name: str,
schema_name: str | Literal["temp"] | None = None,
) -> None:
self._table_name = table_name
self._schema_name = schema_name
self._con = con
con.row_factory = self.orm_table_spec.table_row_factory
def __class_getitem__(cls, params: Any | type[Any] | type[TableSpecType]) -> Any:
# just for convienience, passthrough anything that is not type[TableSpecType]
# to Generic's __class_getitem__ and return it.
# Typically this is for subscript ORMBase with TypeVar or another Generic.
if not (isinstance(params, type) and issubclass(params, TableSpec)):
return super().__class_getitem__(params) # type: ignore
key = (cls, params)
if _cached_type := _parameterized_orm_cache.get(key):
return _GenericAlias(_cached_type, params)
new_parameterized_ormbase: type[ORMBase] = type(
f"{cls.__name__}[{params.__name__}]", (cls,), {}
)
new_parameterized_ormbase.orm_table_spec = params # type: ignore
_parameterized_orm_cache[key] = new_parameterized_ormbase
return _GenericAlias(new_parameterized_ormbase, params)
@property
def orm_con(self) -> sqlite3.Connection:
"""A reference to the underlying sqlite3.Connection.
This is for advanced database execution.
"""
return self._con
@cached_property
def orm_table_name(self) -> str:
"""The unique name of the table for use in sql statement.
If multiple databases are attached to <con> and <schema_name> is availabe,
return "<schema_name>.<table_name>", otherwise return <table_name>.
"""
return (
f"{self._schema_name}.{self._table_name}"
if self._schema_name
else self._table_name
)
def orm_execute(
self, sql_stmt: str, params: tuple[Any, ...] | dict[str, Any] | None = None
) -> list[Any]:
"""Execute one sql statement and get the all the result.
The result will be fetched with fetchall API and returned as it.
This method is inteneded for executing simple sql_stmt with small result.
For complicated sql statement and large result, please use sqlite3.Connection object
exposed by orm_con and manipulate the Cursor object by yourselves.
Args:
sql_stmt (str): The sqlite statement to be executed.
params (tuple[Any, ...] | dict[str, Any] | None, optional): The parameters to be bound
to the sql statement execution. Defaults to None, not passing any params.
Returns:
list[Any]: A list contains all the result entries.
"""
with self._con as con:
if params:
cur = con.execute(sql_stmt, params)
else:
cur = con.execute(sql_stmt)
return cur.fetchall()
def orm_create_table(
self,
*,
allow_existed: bool = False,
strict: bool = False,
without_rowid: bool = False,
) -> None:
"""Create the table defined by this ORM with <orm_table_spec>.
NOTE: strict table option is supported after sqlite3 3.37.
Args:
allow_existed (bool, optional): Do not abort on table already created.
Set True equals to add "IF NOT EXISTS" in the sql statement. Defaults to False.
strict (bool, optional): Enable strict field type check. Defaults to False.
See https://www.sqlite.org/stricttables.html for more details.
without_rowid (bool, optional): Create the table without ROWID. Defaults to False.
See https://www.sqlite.org/withoutrowid.html for more details.
Raises:
sqlite3.DatabaseError on failed sql execution.
"""
with self._con as con:
con.execute(
self.orm_table_spec.table_create_stmt(
self.orm_table_name,
if_not_exists=allow_existed,
strict=strict,
without_rowid=without_rowid,
)
)
def orm_create_index(
self,
*,
index_name: str,
index_keys: tuple[str, ...],
allow_existed: bool = False,
unique: bool = False,
) -> None:
"""Create index according to the input arguments.
Args:
index_name (str): The name of the index.
index_keys (tuple[str, ...]): The columns for the index.
allow_existed (bool, optional): Not abort on index already created. Defaults to False.
unique (bool, optional): Not allow duplicated entries in the index. Defaults to False.
Raises:
sqlite3.DatabaseError on failed sql execution.
"""
index_create_stmt = self.orm_table_spec.table_create_index_stmt(
table_name=self.orm_table_name,
index_name=index_name,
unique=unique,
if_not_exists=allow_existed,
index_cols=index_keys,
)
with self._con as con:
con.execute(index_create_stmt)
def orm_select_entries(
self,
*,
_distinct: bool = False,
_order_by: tuple[str | tuple[str, ORDER_DIRECTION], ...] | None = None,
_limit: int | None = None,
**col_values: Any,
) -> Generator[TableSpecType, None, None]:
"""Select entries from the table accordingly.
Args:
_distinct (bool, optional): Deduplicate and only return unique entries. Defaults to False.
_order_by (tuple[str | tuple[str, ORDER_DIRECTION], ...] | None, optional):
Order the result accordingly. Defaults to None, not sorting the result.
_limit (int | None, optional): Limit the number of result entries. Defaults to None.
Raises:
sqlite3.DatabaseError on failed sql execution.
Yields:
Generator[TableSpecType, None, None]: A generator that can be used to yield entry from result.
"""
table_select_stmt = self.orm_table_spec.table_select_stmt(
select_from=self.orm_table_name,
distinct=_distinct,
order_by=_order_by,
limit=_limit,
where_cols=tuple(col_values),
)
with self._con as con:
_cur = con.execute(table_select_stmt, col_values)
yield from _cur
def orm_select_entry(
self,
*,
_distinct: bool = False,
_order_by: tuple[str | tuple[str, ORDER_DIRECTION], ...] | None = None,
**col_values: Any,
) -> TableSpecType | None:
"""Select exactly one entry from the table accordingly.
NOTE that if the select result contains more than one entry, this method will return
the FIRST one from the result with fetchone API.
Args:
_distinct (bool, optional): Deduplicate and only return unique entries. Defaults to False.
_order_by (tuple[str | tuple[str, ORDER_DIRECTION], ...] | None, optional):
Order the result accordingly. Defaults to None, not sorting the result.
Raises:
sqlite3.DatabaseError on failed sql execution.
Returns:
Exactly one <TableSpecType> entry, or None if not hit.
"""
table_select_stmt = self.orm_table_spec.table_select_stmt(
select_from=self.orm_table_name,
distinct=_distinct,
order_by=_order_by,
where_cols=tuple(col_values),
)
with self._con as con:
_cur = con.execute(table_select_stmt, col_values)
return _cur.fetchone()
def orm_insert_entries(
self, _in: Iterable[TableSpecType], *, or_option: INSERT_OR | None = None
) -> int:
"""Insert entry/entries into this table.
Args:
_in (Iterable[TableSpecType]): A list of entries to insert.
Raises:
ValueError: On invalid types of _in.
sqlite3.DatabaseError: On failed sql execution.
Returns:
int: Number of inserted entries.
"""
insert_stmt = self.orm_table_spec.table_insert_stmt(
insert_into=self.orm_table_name,
or_option=or_option,
)
with self._con as con:
_cur = con.executemany(
insert_stmt, (_row.table_dump_asdict() for _row in _in)
)
return _cur.rowcount
def orm_insert_entry(
self, _in: TableSpecType, *, or_option: INSERT_OR | None = None
) -> int:
"""Insert exactly one entry into this table.
Args:
_in (TableSpecType): The instance of entry to insert.
Raises:
ValueError: On invalid types of _in.
sqlite3.DatabaseError: On failed sql execution.
Returns:
int: Number of inserted entries. In normal case it should be 1.
"""
insert_stmt = self.orm_table_spec.table_insert_stmt(
insert_into=self.orm_table_name,
or_option=or_option,
)
with self._con as con:
_cur = con.execute(insert_stmt, _in.table_dump_asdict())
return _cur.rowcount
@overload
def orm_delete_entries(
self,
*,
_order_by: tuple[str | tuple[str, ORDER_DIRECTION]] | None = None,
_limit: int | None = None,
_returning_cols: None = None,
**cols_value: Any,
) -> int: ...
@overload
def orm_delete_entries(
self,
*,
_order_by: tuple[str | tuple[str, ORDER_DIRECTION]] | None = None,
_limit: int | None = None,
_returning_cols: tuple[str, ...] | Literal["*"],
**cols_value: Any,
) -> Generator[TableSpecType, None, None]: ...
def orm_delete_entries(
self,
*,
_order_by: tuple[str | tuple[str, ORDER_DIRECTION]] | None = None,
_limit: int | None = None,
_returning_cols: tuple[str, ...] | Literal["*"] | None = None,
**cols_value: Any,
) -> int | Generator[TableSpecType, None, None]:
"""Delete entries from the table accordingly.
Args:
_order_by (tuple[str | tuple[str, ORDER_DIRECTION]] | None, optional): Order the matching entries
before executing the deletion, used together with <_limit>. Defaults to None.
_limit (int | None, optional): Only delete <_limit> number of entries. Defaults to None.
_returning_cols (tuple[str, ...] | Literal[, optional): Return the deleted entries on execution.
NOTE that only sqlite3 version >= 3.35 supports returning statement. Defaults to None.
Returns:
int: The num of entries deleted.
Generator[TableSpecType, None, None]: If <_returning_cols> is defined, returns a generator which can
be used to yield the deleted entries from.
"""
delete_stmt = self.orm_table_spec.table_delete_stmt(
delete_from=self.orm_table_name,
limit=_limit,
order_by=_order_by,
returning_cols=_returning_cols,
where_cols=tuple(cols_value),
)
if _returning_cols:
def _gen():
with self._con as con:
_cur = con.execute(delete_stmt, cols_value)
yield from _cur
return _gen()
else:
with self._con as con:
_cur = con.execute(delete_stmt, cols_value)
return _cur.rowcount
ORMBaseType = TypeVar("ORMBaseType", bound=ORMBase)
_global_shutdown = False
def _python_exit():
global _global_shutdown
_global_shutdown = True
atexit.register(_python_exit)
class ORMThreadPoolBase(ORMBase[TableSpecType]):
"""
See https://www.sqlite.org/wal.html#concurrency for more details.
"""
def __init__(
self,
table_name: str,
schema_name: str | None = None,
*,
con_factory: Callable[[], sqlite3.Connection],
number_of_cons: int,
thread_name_prefix: str = "",
) -> None:
self._table_name = table_name
self._schema_name = schema_name
self._thread_id_cons: dict[int, sqlite3.Connection] = {}
def _thread_initializer():
thread_id = threading.get_native_id()
self._thread_id_cons[thread_id] = con = con_factory()
con.row_factory = self.orm_table_spec.table_row_factory
self._pool = ThreadPoolExecutor(
max_workers=number_of_cons,
initializer=_thread_initializer,
thread_name_prefix=thread_name_prefix,
)
@property
def _con(self) -> sqlite3.Connection:
"""Get thread-specific sqlite3 connection."""
return self._thread_id_cons[threading.get_native_id()]
@property
@deprecated("orm_con is not available in thread pool ORM")
def orm_con(self):
"""Not implemented, orm_con is not available in thread pool ORM."""
raise NotImplementedError("orm_con is not available in thread pool ORM")
def orm_pool_shutdown(self, *, wait=True, close_connections=True) -> None:
"""Shutdown the ORM connections thread pool.
It is safe to call this method multiple time.
This method is NOT thread-safe, and should be called at the main thread,
or the thread that creates this thread pool.
Args:
wait (bool, optional): Wait for threads join. Defaults to True.
close_connections (bool, optional): Close all the connections. Defaults to True.
"""
self._pool.shutdown(wait=wait)
if close_connections:
for con in self._thread_id_cons.values():
con.close()
self._thread_id_cons = {}
def orm_execute(
self, sql_stmt: str, params: tuple[Any, ...] | dict[str, Any] | None = None
) -> Future[list[Any]]:
return self._pool.submit(super().orm_execute, sql_stmt, params)
orm_execute.__doc__ = ORMBase.orm_execute.__doc__
def orm_create_table(
self,
*,
allow_existed: bool = False,
strict: bool = False,
without_rowid: bool = False,
) -> Future[None]:
return self._pool.submit(
super().orm_create_table,
allow_existed=allow_existed,
strict=strict,
without_rowid=without_rowid,
)
orm_create_table.__doc__ = ORMBase.orm_create_table.__doc__
def orm_create_index(
self,
*,
index_name: str,
index_keys: tuple[str, ...],
allow_existed: bool = False,
unique: bool = False,
) -> Future[None]:
return self._pool.submit(
super().orm_create_index,
index_name=index_name,
index_keys=index_keys,
allow_existed=allow_existed,
unique=unique,
)
orm_create_index.__doc__ = ORMBase.orm_create_index.__doc__
def orm_select_entries_gen(
self,
*,
_distinct: bool = False,
_order_by: tuple[str | tuple[str, Literal["ASC", "DESC"]], ...] | None = None,
_limit: int | None = None,
**col_values: Any,
) -> Generator[TableSpecType, None, None]:
"""Select multiple entries and return a generator for yielding entries from."""
_queue = queue.SimpleQueue()
def _inner():
global _global_shutdown
try:
for entry in ORMBase.orm_select_entries(
self,
_distinct=_distinct,
_order_by=_order_by,
_limit=_limit,
**col_values,
):
if _global_shutdown:
break
_queue.put_nowait(entry)
except Exception as e:
_queue.put_nowait(e)
finally:
_queue.put_nowait(None)
self._pool.submit(_inner)
def _gen():
while entry := _queue.get():
if isinstance(entry, Exception):
try:
raise entry from None
finally:
del entry
yield entry
return _gen()
def orm_select_entries(
self,
*,
_distinct: bool = False,
_order_by: tuple[str | tuple[str, Literal["ASC", "DESC"]], ...] | None = None,
_limit: int | None = None,
**col_values: Any,
) -> Future[list[TableSpecType]]:
"""Select multiple entries and return all the entries in a list."""
def _inner():
return list(
ORMBase.orm_select_entries(
self,
_distinct=_distinct,
_order_by=_order_by,
_limit=_limit,
**col_values,
)
)
return self._pool.submit(_inner)
def orm_insert_entries(
self, _in: Iterable[TableSpecType], *, or_option: INSERT_OR | None = None
) -> Future[int]:
return self._pool.submit(super().orm_insert_entries, _in, or_option=or_option)
orm_insert_entries.__doc__ = ORMBase.orm_insert_entries.__doc__
def orm_insert_entry(
self, _in: TableSpecType, *, or_option: INSERT_OR | None = None
) -> Future[int]:
return self._pool.submit(super().orm_insert_entry, _in, or_option=or_option)
orm_insert_entry.__doc__ = ORMBase.orm_insert_entry.__doc__
def orm_delete_entries(
self,
*,
_order_by: tuple[str | tuple[str, Literal["ASC", "DESC"]]] | None = None,
_limit: int | None = None,
_returning_cols: tuple[str, ...] | None | Literal["*"] = None,
**cols_value: Any,
) -> Future[int | list[TableSpecType]]:
# NOTE(20240708): currently we don't support generator for delete with RETURNING statement
def _inner():
res = ORMBase.orm_delete_entries(
self,
_order_by=_order_by,
_limit=_limit,
_returning_cols=_returning_cols,
**cols_value,
)
if isinstance(res, int):
return res
return list(res)
return self._pool.submit(_inner)
orm_delete_entries.__doc__ = ORMBase.orm_delete_entries.__doc__
class AsyncORMThreadPoolBase(ORMThreadPoolBase[TableSpecType]):
def __init__(
self,
table_name: str,
schema_name: str | None = None,
*,
con_factory: Callable[[], sqlite3.Connection],
number_of_cons: int,
thread_name_prefix: str = "",
) -> None:
# setup the thread pool
super().__init__(
table_name,
schema_name,
con_factory=con_factory,
number_of_cons=number_of_cons,
thread_name_prefix=thread_name_prefix,
)
self._loop = asyncio.get_running_loop()
def _run_in_pool(
self, func: Callable[P, RT], *args: P.args, **kwargs: P.kwargs
) -> asyncio.Future[RT]:
"""Run normal function in threadpool and track the result async."""
return asyncio.wrap_future(
self._pool.submit(func, *args, **kwargs),
loop=self._loop,
)
@property
@deprecated("orm_con is not available in thread pool ORM")
def orm_con(self):
"""Not implemented, orm_con is not available in thread pool ORM."""
raise NotImplementedError("orm_con is not available in thread pool ORM")
async def orm_execute(
self, sql_stmt: str, params: tuple[Any, ...] | dict[str, Any] | None = None
) -> list[Any]:
return await self._run_in_pool(ORMBase.orm_execute, self, sql_stmt, params)
orm_execute.__doc__ = ORMBase.orm_execute.__doc__
def orm_select_entries_gen(
self,
*,
_distinct: bool = False,
_order_by: tuple[str | tuple[str, Literal["ASC", "DESC"]], ...] | None = None,
_limit: int | None = None,
**col_values: Any,
) -> AsyncGenerator[TableSpecType, Any]:
"""Select multiple entries and return an async generator for yielding entries from."""
_async_queue = asyncio.Queue()
def _inner():
global _global_shutdown
try:
for entry in ORMBase.orm_select_entries(
self,
_distinct=_distinct,
_order_by=_order_by,
_limit=_limit,
**col_values,
):
if _global_shutdown:
break
self._loop.call_soon_threadsafe(_async_queue.put_nowait, entry)
except Exception as e:
self._loop.call_soon_threadsafe(_async_queue.put_nowait, e)
finally:
self._loop.call_soon_threadsafe(_async_queue.put_nowait, None)
self._pool.submit(_inner)
async def _gen():
while entry := await _async_queue.get():
if isinstance(entry, Exception):
try:
raise entry from None
finally:
del entry
yield entry
return _gen()
async def orm_select_entries(
self,
*,
_distinct: bool = False,
_order_by: tuple[str | tuple[str, Literal["ASC", "DESC"]], ...] | None = None,
_limit: int | None = None,
**col_values: Any,
) -> list[TableSpecType]:
"""Select multiple entries and return all the entries in a list."""
def _inner():
return list(
ORMBase.orm_select_entries(
self,
_distinct=_distinct,
_order_by=_order_by,
_limit=_limit,
**col_values,
)
)
return await self._run_in_pool(_inner)
async def orm_select_entry(
self,
*,
_distinct: bool = False,
_order_by: tuple[str | tuple[str, Literal["ASC", "DESC"]], ...] | None = None,
**col_values: Any,
) -> TableSpecType | None:
return await self._run_in_pool(
ORMBase.orm_select_entry,
self,
_distinct=_distinct,
_order_by=_order_by,
**col_values,
)
orm_select_entry.__doc__ = ORMBase.orm_select_entry
async def orm_delete_entries(
self,
*,
_order_by: tuple[str | tuple[str, Literal["ASC", "DESC"]]] | None = None,
_limit: int | None = None,
_returning_cols: tuple[str, ...] | None | Literal["*"] = None,
**cols_value: Any,
) -> list[TableSpecType] | int:
# NOTE(20240708): currently we don't support async generator for delete with RETURNING statement
def _inner():
res = ORMBase.orm_delete_entries(
self,
_order_by=_order_by,
_limit=_limit,
_returning_cols=_returning_cols,
**cols_value,
)
if isinstance(res, int):
return res
return list(res)
return await self._run_in_pool(_inner)
orm_delete_entries.__doc__ = ORMBase.orm_delete_entries.__doc__
async def orm_create_table(
self,
*,
allow_existed: bool = False,
strict: bool = False,
without_rowid: bool = False,
) -> None:
return await self._run_in_pool(
ORMBase.orm_create_table,
self,
allow_existed=allow_existed,
strict=strict,
without_rowid=without_rowid,
)
orm_create_table.__doc__ = ORMBase.orm_create_table.__doc__
async def orm_create_index(
self,
*,
index_name: str,
index_keys: tuple[str, ...],
allow_existed: bool = False,
unique: bool = False,
) -> None:
return await self._run_in_pool(
ORMBase.orm_create_index,
self,
index_name=index_name,
index_keys=index_keys,
allow_existed=allow_existed,
unique=unique,
)
orm_create_index.__doc__ = ORMBase.orm_create_index.__doc__
async def orm_insert_entries(
self, _in: Iterable[TableSpecType], *, or_option: INSERT_OR | None = None
) -> int:
return await self._run_in_pool(
ORMBase.orm_insert_entries, self, _in, or_option=or_option
)
orm_insert_entries.__doc__ = ORMBase.orm_insert_entries.__doc__
async def orm_insert_entry(
self, _in: TableSpecType, *, or_option: INSERT_OR | None = None
) -> int:
return await self._run_in_pool(
ORMBase.orm_insert_entry, self, _in, or_option=or_option
)
orm_insert_entry.__doc__ = ORMBase.orm_insert_entry.__doc__