caddix 1.0.0__py3-none-any.whl
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.
- caddix/__init__.py +33 -0
- caddix/base.py +517 -0
- caddix/config.py +59 -0
- caddix/pool.py +93 -0
- caddix/py.typed +0 -0
- caddix/stores.py +2 -0
- caddix/utils.py +343 -0
- caddix-1.0.0.dist-info/METADATA +873 -0
- caddix-1.0.0.dist-info/RECORD +11 -0
- caddix-1.0.0.dist-info/WHEEL +4 -0
- caddix-1.0.0.dist-info/licenses/LICENSE +21 -0
caddix/__init__.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
#!/bin/python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
# vim: set fileencoding=utf-8 :
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
from psycopg.rows import class_row, dict_row, namedtuple_row, scalar_row, tuple_row
|
|
7
|
+
|
|
8
|
+
from .base import DatabaseSession, CaddixError, CaddixSessionError, TuskerError, TuskerSessionError
|
|
9
|
+
from .config import Configs as Setup
|
|
10
|
+
from .pool import PGPool
|
|
11
|
+
|
|
12
|
+
__title__ = "caddix"
|
|
13
|
+
__description__ = "Caddix is a helper library for Python designed to make working with PostgreSQL databases easier, faster, and safer."
|
|
14
|
+
__author__ = "Marcus Gros"
|
|
15
|
+
__email__ = "marcus-gros@freenet.de"
|
|
16
|
+
__copyright__ = "Copyright 2026 Marcus Gros"
|
|
17
|
+
__license__ = "MIT"
|
|
18
|
+
__version__ = "1.0.0"
|
|
19
|
+
__requirements__ = ["psycopg"]
|
|
20
|
+
__all__ = [
|
|
21
|
+
"Setup",
|
|
22
|
+
"PGPool",
|
|
23
|
+
"DatabaseSession",
|
|
24
|
+
"CaddixError",
|
|
25
|
+
"CaddixSessionError",
|
|
26
|
+
"TuskerError",
|
|
27
|
+
"TuskerSessionError",
|
|
28
|
+
"dict_row",
|
|
29
|
+
"tuple_row",
|
|
30
|
+
"scalar_row",
|
|
31
|
+
"class_row",
|
|
32
|
+
"namedtuple_row",
|
|
33
|
+
]
|
caddix/base.py
ADDED
|
@@ -0,0 +1,517 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from typing import Any, Sequence
|
|
3
|
+
|
|
4
|
+
import psycopg
|
|
5
|
+
from psycopg import sql
|
|
6
|
+
from psycopg.pq import TransactionStatus
|
|
7
|
+
from psycopg.rows import dict_row, scalar_row, tuple_row
|
|
8
|
+
from .config import Configs
|
|
9
|
+
from .pool import PGPool
|
|
10
|
+
from .utils import (
|
|
11
|
+
build_select_query,
|
|
12
|
+
build_insert_query,
|
|
13
|
+
build_update_query,
|
|
14
|
+
build_delete_query,
|
|
15
|
+
build_update_batch_query,
|
|
16
|
+
build_upsert_batch_query,
|
|
17
|
+
build_call_func_query,
|
|
18
|
+
build_call_proc_query,
|
|
19
|
+
_sql_table,
|
|
20
|
+
_sql_returning,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
log = logging.getLogger('caddix')
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class CaddixError(Exception):
|
|
27
|
+
def __init__(self, orig: Exception, stm: str, params: Any, verbose: bool = True):
|
|
28
|
+
self.orig = orig
|
|
29
|
+
if verbose:
|
|
30
|
+
msg = [
|
|
31
|
+
stm, str(params),
|
|
32
|
+
f'{orig.__class__.__name__}: {orig}'
|
|
33
|
+
]
|
|
34
|
+
else:
|
|
35
|
+
diag = getattr(orig, 'diag', None)
|
|
36
|
+
primary_msg = getattr(diag, 'message_primary', None) if diag else None
|
|
37
|
+
if primary_msg:
|
|
38
|
+
msg = [f'{orig.__class__.__name__}: {primary_msg}']
|
|
39
|
+
else:
|
|
40
|
+
msg = [f'{orig.__class__.__name__}']
|
|
41
|
+
super().__init__('\n'.join(msg))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class CaddixSessionError(Exception):
|
|
45
|
+
pass
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
# Backward compatibility aliases
|
|
49
|
+
TuskerError = CaddixError
|
|
50
|
+
TuskerSessionError = CaddixSessionError
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class DatabaseSession:
|
|
54
|
+
"""
|
|
55
|
+
Represents a database session to manage connections and execute queries.
|
|
56
|
+
|
|
57
|
+
The DatabaseSession class facilitates interaction with a PostgreSQL database using a connection pool.
|
|
58
|
+
It provides methods for executing queries, fetching results, and performing various database operations.
|
|
59
|
+
This class also supports context management, which ensures that resources are properly cleaned up
|
|
60
|
+
when the session scope completes.
|
|
61
|
+
|
|
62
|
+
:ivar cursor_factory: Defines the row factory used for fetching results, allowing custom transformations
|
|
63
|
+
of query results into specific formats or types.
|
|
64
|
+
:type cursor_factory: callable
|
|
65
|
+
:ivar con: The database connection object used for all database interactions through this session.
|
|
66
|
+
:type con: psycopg.Connection
|
|
67
|
+
:ivar cur: The database cursor used to execute and fetch query results.
|
|
68
|
+
:type cur: psycopg.Cursor
|
|
69
|
+
:ivar last_query: Stores the last executed query string. Useful for debugging or logging purposes.
|
|
70
|
+
:type last_query: str
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
def __init__(self, configname='default', cursor_factory=None):
|
|
74
|
+
self.configname = configname
|
|
75
|
+
self.cnf = Configs.configs[configname]
|
|
76
|
+
|
|
77
|
+
self.cursor_factory = self.cnf['default_rowfactory']
|
|
78
|
+
if cursor_factory:
|
|
79
|
+
self.cursor_factory = cursor_factory
|
|
80
|
+
|
|
81
|
+
self.pool = PGPool(configname)
|
|
82
|
+
self.con = self.pool.con
|
|
83
|
+
self.cur = self.con.cursor()
|
|
84
|
+
self.cur.row_factory = self.cursor_factory
|
|
85
|
+
self.last_query: str | None = None
|
|
86
|
+
|
|
87
|
+
def __enter__(self):
|
|
88
|
+
return self
|
|
89
|
+
|
|
90
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
91
|
+
self.close()
|
|
92
|
+
|
|
93
|
+
def close(self):
|
|
94
|
+
if hasattr(self, 'cur') and self.cur is not None and not self.cur.closed:
|
|
95
|
+
try:
|
|
96
|
+
self.cur.close()
|
|
97
|
+
except psycopg.Error:
|
|
98
|
+
pass
|
|
99
|
+
if hasattr(self, 'con') and self.con is not None:
|
|
100
|
+
try:
|
|
101
|
+
if not self.con.closed:
|
|
102
|
+
self.con.rollback()
|
|
103
|
+
except psycopg.Error:
|
|
104
|
+
pass
|
|
105
|
+
if hasattr(self, 'pool') and self.pool is not None:
|
|
106
|
+
self.pool.release(self.con, self.pool.expire)
|
|
107
|
+
self.pool = None
|
|
108
|
+
|
|
109
|
+
@staticmethod
|
|
110
|
+
def __kwargs__(kwargs):
|
|
111
|
+
if not kwargs:
|
|
112
|
+
return {}
|
|
113
|
+
return {
|
|
114
|
+
(k[1:] if k.startswith('_') and len(k) > 1 and not k.startswith('__') else k): v
|
|
115
|
+
for k, v in kwargs.items()
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
def commit(self):
|
|
119
|
+
self.con.commit()
|
|
120
|
+
|
|
121
|
+
def rollback(self):
|
|
122
|
+
self.con.rollback()
|
|
123
|
+
|
|
124
|
+
def execute(self, query, *args, **kwargs):
|
|
125
|
+
self.last_query = str(query)
|
|
126
|
+
clean_kwargs = self.__kwargs__(kwargs)
|
|
127
|
+
try:
|
|
128
|
+
if args:
|
|
129
|
+
params = args[0] if len(args) == 1 and isinstance(args[0], (tuple, list, dict)) else args
|
|
130
|
+
self.cur.execute(query, params)
|
|
131
|
+
elif clean_kwargs:
|
|
132
|
+
self.cur.execute(query, clean_kwargs)
|
|
133
|
+
else:
|
|
134
|
+
self.cur.execute(query)
|
|
135
|
+
except Exception as e:
|
|
136
|
+
params = args if args else clean_kwargs
|
|
137
|
+
raise CaddixError(e, self.last_query, params, verbose=self.cnf.get('verbose', True)) from None
|
|
138
|
+
|
|
139
|
+
def executemany(self, query, values):
|
|
140
|
+
self.last_query = str(query)
|
|
141
|
+
verbose = self.cnf.get('verbose', True)
|
|
142
|
+
try:
|
|
143
|
+
self.cur.executemany(query, values)
|
|
144
|
+
except Exception as e:
|
|
145
|
+
raise CaddixError(e, self.last_query, values, verbose=verbose) from None
|
|
146
|
+
|
|
147
|
+
# ===== fetch from cursor after executing =====
|
|
148
|
+
|
|
149
|
+
def fetchone(self):
|
|
150
|
+
if not self.cur.description:
|
|
151
|
+
return None
|
|
152
|
+
return self.cur.fetchone()
|
|
153
|
+
|
|
154
|
+
def fetchall(self):
|
|
155
|
+
if not self.cur.description:
|
|
156
|
+
return []
|
|
157
|
+
return self.cur.fetchall()
|
|
158
|
+
|
|
159
|
+
def fetchmany(self, size):
|
|
160
|
+
if not self.cur.description:
|
|
161
|
+
return []
|
|
162
|
+
return self.cur.fetchmany(size)
|
|
163
|
+
|
|
164
|
+
def fetchscalar(self):
|
|
165
|
+
if not self.cur.description:
|
|
166
|
+
return None
|
|
167
|
+
factory = self.cur.row_factory
|
|
168
|
+
try:
|
|
169
|
+
self.cur.row_factory = scalar_row
|
|
170
|
+
return self.fetchone()
|
|
171
|
+
finally:
|
|
172
|
+
self.cur.row_factory = factory
|
|
173
|
+
|
|
174
|
+
def fetchlist(self):
|
|
175
|
+
if not self.cur.description:
|
|
176
|
+
return []
|
|
177
|
+
factory = self.cur.row_factory
|
|
178
|
+
try:
|
|
179
|
+
self.cur.row_factory = tuple_row
|
|
180
|
+
res = self.fetchall()
|
|
181
|
+
return [v[0] for v in res] if res else []
|
|
182
|
+
finally:
|
|
183
|
+
self.cur.row_factory = factory
|
|
184
|
+
|
|
185
|
+
def fetchdict(self):
|
|
186
|
+
if not self.cur.description:
|
|
187
|
+
return {}
|
|
188
|
+
factory = self.cur.row_factory
|
|
189
|
+
try:
|
|
190
|
+
self.cur.row_factory = tuple_row
|
|
191
|
+
res = self.fetchall()
|
|
192
|
+
return {k: v for k, v in res} if res else {}
|
|
193
|
+
finally:
|
|
194
|
+
self.cur.row_factory = factory
|
|
195
|
+
|
|
196
|
+
# ===== execute and return fetched row/s =====
|
|
197
|
+
|
|
198
|
+
def execute_fetchone(self, query, *args, **kwargs):
|
|
199
|
+
self.execute(query, *args, **kwargs)
|
|
200
|
+
return self.fetchone()
|
|
201
|
+
|
|
202
|
+
def execute_fetchall(self, query, *args, **kwargs):
|
|
203
|
+
self.execute(query, *args, **kwargs)
|
|
204
|
+
return self.fetchall()
|
|
205
|
+
|
|
206
|
+
def execute_fetchmany(self, query, size, *args, **kwargs):
|
|
207
|
+
self.execute(query, *args, **kwargs)
|
|
208
|
+
return self.fetchmany(size)
|
|
209
|
+
|
|
210
|
+
def execute_fetchscalar(self, query, *args, **kwargs):
|
|
211
|
+
self.execute(query, *args, **kwargs)
|
|
212
|
+
return self.fetchscalar()
|
|
213
|
+
|
|
214
|
+
def execute_fetchdict(self, query, *args, **kwargs):
|
|
215
|
+
self.execute(query, *args, **kwargs)
|
|
216
|
+
return self.fetchdict()
|
|
217
|
+
|
|
218
|
+
def execute_fetchlist(self, query, *args, **kwargs):
|
|
219
|
+
self.execute(query, *args, **kwargs)
|
|
220
|
+
return self.fetchlist()
|
|
221
|
+
|
|
222
|
+
def _execute_select(self, tablename: str, columns: Sequence[str] | str = ('*',), **kwargs):
|
|
223
|
+
kwargs = self.__kwargs__(kwargs)
|
|
224
|
+
query, params = build_select_query(con=self.con, tablename=tablename, columns=columns, **kwargs)
|
|
225
|
+
self.execute(query, **params)
|
|
226
|
+
|
|
227
|
+
def select_all(self, tablename: str, columns: Sequence[str] | str = ('*',), **kwargs):
|
|
228
|
+
self._execute_select(tablename, columns=columns, **kwargs)
|
|
229
|
+
return self.fetchall()
|
|
230
|
+
|
|
231
|
+
def select_one(self, tablename: str, columns: Sequence[str] | str = ('*',), **kwargs):
|
|
232
|
+
self._execute_select(tablename, columns=columns, **kwargs)
|
|
233
|
+
return self.fetchone()
|
|
234
|
+
|
|
235
|
+
def select_scalar(self, tablename: str, column: str, **kwargs):
|
|
236
|
+
self._execute_select(tablename, columns=[column], **kwargs)
|
|
237
|
+
return self.fetchscalar()
|
|
238
|
+
|
|
239
|
+
def select_many(self, tablename: str, size: int, columns: Sequence[str] | str = ('*',), **kwargs):
|
|
240
|
+
if size is None or size <= 0:
|
|
241
|
+
raise CaddixSessionError('select_many() requires size > 0')
|
|
242
|
+
self._execute_select(tablename, columns=columns, **kwargs)
|
|
243
|
+
return self.fetchmany(size)
|
|
244
|
+
|
|
245
|
+
def select_list(self, tablename: str, column: str, **kwargs):
|
|
246
|
+
self._execute_select(tablename, columns=[column], **kwargs)
|
|
247
|
+
return self.fetchlist()
|
|
248
|
+
|
|
249
|
+
def select_dict(self, tablename: str, column_key: str, column_value: str, **kwargs):
|
|
250
|
+
self._execute_select(tablename, columns=[column_key, column_value], **kwargs)
|
|
251
|
+
return self.fetchdict()
|
|
252
|
+
|
|
253
|
+
# ===== for easy data-manipulation =====
|
|
254
|
+
|
|
255
|
+
def insert(self, tablename: str, returning=None, **kwargs):
|
|
256
|
+
kwargs = self.__kwargs__(kwargs)
|
|
257
|
+
query, safe_params = build_insert_query(self.con, tablename, kwargs, returning=returning)
|
|
258
|
+
self.execute(query, **safe_params)
|
|
259
|
+
if returning:
|
|
260
|
+
return self.fetchone()
|
|
261
|
+
return None
|
|
262
|
+
|
|
263
|
+
def update(self, tablename: str, values: dict[str, Any] | None = None, returning=None, check_changes: bool = False, **kwargs):
|
|
264
|
+
kwargs = self.__kwargs__(kwargs)
|
|
265
|
+
values = {} if values is None else self.__kwargs__(values)
|
|
266
|
+
query, safe_params, has_set = build_update_query(
|
|
267
|
+
self.con, tablename, values, returning=returning, check_changes=check_changes, **kwargs
|
|
268
|
+
)
|
|
269
|
+
if not has_set:
|
|
270
|
+
return [] if returning else 0
|
|
271
|
+
|
|
272
|
+
self.execute(query, **safe_params)
|
|
273
|
+
if returning:
|
|
274
|
+
return self.fetchall()
|
|
275
|
+
return None
|
|
276
|
+
|
|
277
|
+
def delete(self, tablename: str, returning=None, **kwargs):
|
|
278
|
+
kwargs = self.__kwargs__(kwargs)
|
|
279
|
+
query, safe_params = build_delete_query(self.con, tablename, returning=returning, **kwargs)
|
|
280
|
+
self.execute(query, **safe_params)
|
|
281
|
+
if returning:
|
|
282
|
+
return self.fetchall()
|
|
283
|
+
return None
|
|
284
|
+
|
|
285
|
+
# ===== for easy bulk data-manipulation =====
|
|
286
|
+
|
|
287
|
+
def insert_batch(self, tablename, values, returning=None):
|
|
288
|
+
if not values:
|
|
289
|
+
return 0
|
|
290
|
+
|
|
291
|
+
clean_values = [self.__kwargs__(v) for v in values]
|
|
292
|
+
first_row = clean_values[0]
|
|
293
|
+
columns = list(first_row.keys())
|
|
294
|
+
|
|
295
|
+
ret_sql = _sql_returning(returning)
|
|
296
|
+
if not ret_sql:
|
|
297
|
+
sql_copy = sql.SQL("COPY {table} ({cols}) FROM STDIN").format(
|
|
298
|
+
table=_sql_table(tablename),
|
|
299
|
+
cols=sql.SQL(", ").join(map(sql.Identifier, columns))
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
with self.cur.copy(sql_copy) as copy:
|
|
303
|
+
for row in clean_values:
|
|
304
|
+
copy.write_row([row.get(col) for col in columns])
|
|
305
|
+
|
|
306
|
+
return self.cur.rowcount
|
|
307
|
+
|
|
308
|
+
columns_sql = sql.SQL(', ').join(map(sql.Identifier, columns))
|
|
309
|
+
placeholders_sql = sql.SQL(', ').join(map(lambda c: sql.SQL("%({})s").format(sql.SQL(c)), columns))
|
|
310
|
+
|
|
311
|
+
query = sql.SQL("INSERT INTO {table} ({cols}) VALUES ({vals})").format(
|
|
312
|
+
table=_sql_table(tablename),
|
|
313
|
+
cols=columns_sql,
|
|
314
|
+
vals=placeholders_sql
|
|
315
|
+
)
|
|
316
|
+
|
|
317
|
+
query += sql.SQL(" RETURNING ") + ret_sql
|
|
318
|
+
|
|
319
|
+
self.executemany(query, clean_values)
|
|
320
|
+
return self.fetchall()
|
|
321
|
+
|
|
322
|
+
def update_batch(self, tablename, values, update_columns, where_columns, returning=None, check_changes: bool = False):
|
|
323
|
+
if not values:
|
|
324
|
+
return 0
|
|
325
|
+
|
|
326
|
+
clean_values = [self.__kwargs__(v) for v in values]
|
|
327
|
+
first_row = clean_values[0]
|
|
328
|
+
|
|
329
|
+
if update_columns == '*' or (isinstance(update_columns, (list, tuple)) and len(update_columns) == 1 and update_columns[0] == '*'):
|
|
330
|
+
target_update_columns = [col for col in first_row.keys() if col not in where_columns]
|
|
331
|
+
elif isinstance(update_columns, str):
|
|
332
|
+
target_update_columns = [c.strip() for c in update_columns.split(',') if c.strip()]
|
|
333
|
+
else:
|
|
334
|
+
target_update_columns = list(update_columns)
|
|
335
|
+
|
|
336
|
+
if isinstance(where_columns, str):
|
|
337
|
+
target_where_columns = [c.strip() for c in where_columns.split(',') if c.strip()]
|
|
338
|
+
else:
|
|
339
|
+
target_where_columns = list(where_columns)
|
|
340
|
+
|
|
341
|
+
for col in list(target_update_columns) + list(target_where_columns):
|
|
342
|
+
if col not in first_row:
|
|
343
|
+
raise CaddixSessionError(f'Column "{col}" not found in values')
|
|
344
|
+
|
|
345
|
+
query = build_update_batch_query(
|
|
346
|
+
self.con, tablename, target_update_columns, target_where_columns, returning=returning, check_changes=check_changes
|
|
347
|
+
)
|
|
348
|
+
|
|
349
|
+
self.executemany(query, clean_values)
|
|
350
|
+
|
|
351
|
+
if returning:
|
|
352
|
+
return self.fetchall()
|
|
353
|
+
return self.cur.rowcount
|
|
354
|
+
|
|
355
|
+
def upsert_batch(self, tablename, values, conflict_columns=None, update_columns='*', returning=None, conflict_target=None, check_changes: bool = False):
|
|
356
|
+
if not values:
|
|
357
|
+
return 0
|
|
358
|
+
|
|
359
|
+
if conflict_columns is None and conflict_target is not None:
|
|
360
|
+
conflict_columns = conflict_target
|
|
361
|
+
|
|
362
|
+
if conflict_columns is None:
|
|
363
|
+
raise CaddixSessionError('conflict_columns is required for upsert_batch')
|
|
364
|
+
|
|
365
|
+
clean_values = [self.__kwargs__(v) for v in values]
|
|
366
|
+
first_row = clean_values[0]
|
|
367
|
+
columns = list(first_row.keys())
|
|
368
|
+
|
|
369
|
+
if isinstance(conflict_columns, str):
|
|
370
|
+
target_conflict_columns = [c.strip() for c in conflict_columns.split(',') if c.strip()]
|
|
371
|
+
else:
|
|
372
|
+
target_conflict_columns = list(conflict_columns)
|
|
373
|
+
|
|
374
|
+
query = build_upsert_batch_query(
|
|
375
|
+
self.con, tablename, columns, target_conflict_columns, update_columns=update_columns, returning=returning, check_changes=check_changes
|
|
376
|
+
)
|
|
377
|
+
|
|
378
|
+
self.executemany(query, clean_values)
|
|
379
|
+
|
|
380
|
+
if returning:
|
|
381
|
+
return self.fetchall()
|
|
382
|
+
return self.cur.rowcount
|
|
383
|
+
|
|
384
|
+
# ===== function & procedure execution =====
|
|
385
|
+
|
|
386
|
+
def call_func(self, funcname: str, *args, **kwargs):
|
|
387
|
+
"""
|
|
388
|
+
Executes a PostgreSQL function (SELECT * FROM funcname(...)) and returns all result rows.
|
|
389
|
+
"""
|
|
390
|
+
return self.func_all(funcname, *args, **kwargs)
|
|
391
|
+
|
|
392
|
+
def call_function(self, funcname: str, *args, **kwargs):
|
|
393
|
+
"""
|
|
394
|
+
Alias for call_func.
|
|
395
|
+
"""
|
|
396
|
+
return self.call_func(funcname, *args, **kwargs)
|
|
397
|
+
|
|
398
|
+
def _execute_func(self, funcname: str, as_table: bool, *args, **kwargs):
|
|
399
|
+
kwargs = self.__kwargs__(kwargs)
|
|
400
|
+
query, params = build_call_func_query(self.con, funcname, as_table, *args, **kwargs)
|
|
401
|
+
self.execute(query, **params)
|
|
402
|
+
|
|
403
|
+
def func_all(self, funcname: str, *args, **kwargs):
|
|
404
|
+
"""
|
|
405
|
+
Executes a PostgreSQL function and returns all result rows (via fetchall).
|
|
406
|
+
"""
|
|
407
|
+
self._execute_func(funcname, True, *args, **kwargs)
|
|
408
|
+
return self.fetchall()
|
|
409
|
+
|
|
410
|
+
def func_one(self, funcname: str, *args, **kwargs):
|
|
411
|
+
"""
|
|
412
|
+
Executes a PostgreSQL function and returns a single result row (via fetchone).
|
|
413
|
+
"""
|
|
414
|
+
self._execute_func(funcname, True, *args, **kwargs)
|
|
415
|
+
return self.fetchone()
|
|
416
|
+
|
|
417
|
+
def func_scalar(self, funcname: str, *args, **kwargs):
|
|
418
|
+
"""
|
|
419
|
+
Executes a PostgreSQL function (SELECT funcname(...)) and returns a single scalar value.
|
|
420
|
+
"""
|
|
421
|
+
self._execute_func(funcname, False, *args, **kwargs)
|
|
422
|
+
return self.fetchscalar()
|
|
423
|
+
|
|
424
|
+
def func_many(self, funcname: str, size: int, *args, **kwargs):
|
|
425
|
+
"""
|
|
426
|
+
Executes a PostgreSQL function and returns up to `size` result rows (via fetchmany).
|
|
427
|
+
"""
|
|
428
|
+
if size is None or size <= 0:
|
|
429
|
+
raise CaddixSessionError('func_many() requires size > 0')
|
|
430
|
+
self._execute_func(funcname, True, *args, **kwargs)
|
|
431
|
+
return self.fetchmany(size)
|
|
432
|
+
|
|
433
|
+
def func_list(self, funcname: str, *args, **kwargs):
|
|
434
|
+
"""
|
|
435
|
+
Executes a PostgreSQL function and returns the first column of all rows as a list.
|
|
436
|
+
"""
|
|
437
|
+
self._execute_func(funcname, True, *args, **kwargs)
|
|
438
|
+
return self.fetchlist()
|
|
439
|
+
|
|
440
|
+
def func_dict(self, funcname: str, *args, **kwargs):
|
|
441
|
+
"""
|
|
442
|
+
Executes a PostgreSQL function returning 2 columns and returns them as a key-value dictionary.
|
|
443
|
+
"""
|
|
444
|
+
self._execute_func(funcname, True, *args, **kwargs)
|
|
445
|
+
return self.fetchdict()
|
|
446
|
+
|
|
447
|
+
def call_proc(self, procname: str, *args, **kwargs):
|
|
448
|
+
"""
|
|
449
|
+
Executes a PostgreSQL stored procedure (CALL procname(...)).
|
|
450
|
+
Returns output/INOUT parameters if any, or None.
|
|
451
|
+
"""
|
|
452
|
+
kwargs = self.__kwargs__(kwargs)
|
|
453
|
+
query, params = build_call_proc_query(self.con, procname, *args, **kwargs)
|
|
454
|
+
self.execute(query, **params)
|
|
455
|
+
if self.cur.description:
|
|
456
|
+
return self.fetchone()
|
|
457
|
+
return None
|
|
458
|
+
|
|
459
|
+
def call_procedure(self, procname: str, *args, **kwargs):
|
|
460
|
+
"""
|
|
461
|
+
Alias for call_proc.
|
|
462
|
+
"""
|
|
463
|
+
return self.call_proc(procname, *args, **kwargs)
|
|
464
|
+
|
|
465
|
+
# ===== other helpful thinks =====
|
|
466
|
+
|
|
467
|
+
def exists(self, tablename: str, **kwargs) -> bool:
|
|
468
|
+
try:
|
|
469
|
+
self._execute_select(tablename, ('*',), **kwargs)
|
|
470
|
+
return self.fetchone() is not None
|
|
471
|
+
except CaddixError as e:
|
|
472
|
+
if isinstance(getattr(e, 'orig', None), psycopg.errors.UndefinedTable):
|
|
473
|
+
try:
|
|
474
|
+
if not self.con.closed and self.con.info.transaction_status != TransactionStatus.IDLE:
|
|
475
|
+
self.con.rollback()
|
|
476
|
+
except psycopg.Error:
|
|
477
|
+
pass
|
|
478
|
+
return False
|
|
479
|
+
raise
|
|
480
|
+
|
|
481
|
+
def tabledesc(self, tablename, asdict=False):
|
|
482
|
+
factory = self.cur.row_factory
|
|
483
|
+
try:
|
|
484
|
+
self.cur.row_factory = dict_row
|
|
485
|
+
self.execute("""
|
|
486
|
+
SELECT f.attname AS name,
|
|
487
|
+
pg_catalog.format_type(f.atttypid, f.atttypmod) AS type,
|
|
488
|
+
CASE WHEN f.attlen > -1 THEN f.attlen END AS length,
|
|
489
|
+
f.attnotnull AS notnull,
|
|
490
|
+
CASE WHEN p.contype = 'p' THEN true ELSE false END AS primarykey,
|
|
491
|
+
CASE WHEN p.contype = 'u' THEN true ELSE false END AS uniquekey,
|
|
492
|
+
CASE WHEN p.contype = 'f' THEN true ELSE false end AS foreignkey,
|
|
493
|
+
CASE WHEN f.atthasdef = 't' THEN pg_get_expr(d.adbin, d.adrelid) END AS default
|
|
494
|
+
FROM pg_attribute f
|
|
495
|
+
JOIN pg_class c ON c.oid = f.attrelid
|
|
496
|
+
JOIN pg_type t ON t.oid = f.atttypid
|
|
497
|
+
LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum
|
|
498
|
+
LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
499
|
+
LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY (p.conkey)
|
|
500
|
+
LEFT JOIN pg_class AS g ON p.confrelid = g.oid
|
|
501
|
+
WHERE c.relkind = 'r'::char
|
|
502
|
+
AND concat(n.nspname || '.' || c.relname) in (concat('public.' || %(tablename)s), %(tablename)s)
|
|
503
|
+
AND f.attnum > 0
|
|
504
|
+
ORDER BY f.attnum
|
|
505
|
+
""", tablename=tablename)
|
|
506
|
+
rows = self.fetchall()
|
|
507
|
+
finally:
|
|
508
|
+
self.cur.row_factory = factory
|
|
509
|
+
|
|
510
|
+
if asdict:
|
|
511
|
+
return {
|
|
512
|
+
row['name']: {
|
|
513
|
+
k: row[k] for k in ('type', 'length', 'notnull', 'primarykey', 'uniquekey', 'foreignkey', 'default')
|
|
514
|
+
}
|
|
515
|
+
for row in rows or []
|
|
516
|
+
}
|
|
517
|
+
return rows
|
caddix/config.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
from psycopg.conninfo import make_conninfo
|
|
2
|
+
from psycopg.rows import dict_row
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class Configs:
|
|
6
|
+
"""
|
|
7
|
+
Container for managing database configuration settings.
|
|
8
|
+
|
|
9
|
+
The Configs class allows for easy creation, storage, and retrieval
|
|
10
|
+
of database configuration settings. It supports setting up
|
|
11
|
+
connections to PostgreSQL databases with customizable parameters
|
|
12
|
+
such as timeout, application name, and maximum allowed connections.
|
|
13
|
+
Multiple configurations can be managed under different names.
|
|
14
|
+
|
|
15
|
+
:ivar configs: Stores all configurations with their respective names.
|
|
16
|
+
:type configs: dict
|
|
17
|
+
"""
|
|
18
|
+
configs = {}
|
|
19
|
+
|
|
20
|
+
def __init__(self, databasename=None, username=None, password=None, hostname=None, port=5432,
|
|
21
|
+
name='default', connect_timeout=10, verbose=True,
|
|
22
|
+
application_name='python', ttl=10, max_connections=10,
|
|
23
|
+
default_rowfactory=dict_row, cursor_factory=None):
|
|
24
|
+
if cursor_factory is not None:
|
|
25
|
+
default_rowfactory = cursor_factory
|
|
26
|
+
|
|
27
|
+
if databasename is not None:
|
|
28
|
+
self.configs[name] = {
|
|
29
|
+
'dbname': databasename,
|
|
30
|
+
'user': username,
|
|
31
|
+
'dsn': make_conninfo(
|
|
32
|
+
dbname=databasename,
|
|
33
|
+
user=username,
|
|
34
|
+
password=password,
|
|
35
|
+
host=hostname,
|
|
36
|
+
port=port,
|
|
37
|
+
connect_timeout=connect_timeout,
|
|
38
|
+
application_name=application_name
|
|
39
|
+
),
|
|
40
|
+
'ttl': ttl,
|
|
41
|
+
'default_rowfactory': default_rowfactory,
|
|
42
|
+
'max_connections': max_connections,
|
|
43
|
+
'verbose': verbose
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
def __getitem__(self, item):
|
|
47
|
+
return self.configs[item]
|
|
48
|
+
|
|
49
|
+
def __setitem__(self, key, value):
|
|
50
|
+
self.configs[key] = value
|
|
51
|
+
|
|
52
|
+
def __contains__(self, item):
|
|
53
|
+
return item in self.configs
|
|
54
|
+
|
|
55
|
+
def __len__(self):
|
|
56
|
+
return len(self.configs)
|
|
57
|
+
|
|
58
|
+
def get(self, item, default=None):
|
|
59
|
+
return self.configs.get(item, default)
|
caddix/pool.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import queue
|
|
2
|
+
import time
|
|
3
|
+
|
|
4
|
+
import psycopg
|
|
5
|
+
from psycopg.pq import TransactionStatus
|
|
6
|
+
|
|
7
|
+
from .config import Configs
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class PGPool:
|
|
11
|
+
"""
|
|
12
|
+
Manages connections to a PostgreSQL database using a configurable connection pooling mechanism.
|
|
13
|
+
|
|
14
|
+
This class provides a pooling mechanism for managing PostgreSQL database connections, which
|
|
15
|
+
ensures that connections can be efficiently reused. It supports configurations that define
|
|
16
|
+
connection details and time-to-live (TTL) values for individual connections. The pooling mechanism
|
|
17
|
+
is implemented using Python's `queue.Queue` for thread-safety when accessing pooled connections.
|
|
18
|
+
|
|
19
|
+
:ivar configname: The name of the configuration to use for the database connection.
|
|
20
|
+
:type configname: str
|
|
21
|
+
:ivar queue: A thread-safe queue used to store and manage connections for the specified configuration.
|
|
22
|
+
:type queue: queue.Queue
|
|
23
|
+
:ivar con: The current database connection object from the pool. A new connection may be created
|
|
24
|
+
if no valid connection exists or if the TTL has expired.
|
|
25
|
+
:type con: psycopg.Connection
|
|
26
|
+
:ivar expire: The expiration time for the current connection. Connections are assigned a TTL
|
|
27
|
+
after which they are refreshed.
|
|
28
|
+
:type expire: float
|
|
29
|
+
"""
|
|
30
|
+
queues = {}
|
|
31
|
+
|
|
32
|
+
def __init__(self, configname='default'):
|
|
33
|
+
self.configname = configname
|
|
34
|
+
cnf = Configs.configs[configname]
|
|
35
|
+
dsn = cnf['dsn']
|
|
36
|
+
ttl = cnf.get('ttl', 10)
|
|
37
|
+
max_connections = cnf.get('max_connections', 10)
|
|
38
|
+
self.queue = self.queues.setdefault(configname, queue.Queue(maxsize=max_connections))
|
|
39
|
+
|
|
40
|
+
self.con = None
|
|
41
|
+
self.expire = None
|
|
42
|
+
|
|
43
|
+
while True:
|
|
44
|
+
try:
|
|
45
|
+
con, expire = self.queue.get_nowait()
|
|
46
|
+
# Discard closed or broken connections
|
|
47
|
+
if con.closed or getattr(con, 'broken', False):
|
|
48
|
+
continue
|
|
49
|
+
# Discard expired connections
|
|
50
|
+
if expire < time.time():
|
|
51
|
+
try:
|
|
52
|
+
con.close()
|
|
53
|
+
except psycopg.Error:
|
|
54
|
+
pass
|
|
55
|
+
continue
|
|
56
|
+
# Ensure clean transaction state
|
|
57
|
+
try:
|
|
58
|
+
if con.info.transaction_status != TransactionStatus.IDLE:
|
|
59
|
+
con.rollback()
|
|
60
|
+
except psycopg.Error:
|
|
61
|
+
try:
|
|
62
|
+
con.close()
|
|
63
|
+
except psycopg.Error:
|
|
64
|
+
pass
|
|
65
|
+
continue
|
|
66
|
+
|
|
67
|
+
self.con = con
|
|
68
|
+
self.expire = expire
|
|
69
|
+
break
|
|
70
|
+
except queue.Empty:
|
|
71
|
+
self.con = psycopg.connect(conninfo=dsn)
|
|
72
|
+
self.expire = time.time() + ttl
|
|
73
|
+
break
|
|
74
|
+
|
|
75
|
+
def __enter__(self):
|
|
76
|
+
return self
|
|
77
|
+
|
|
78
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
79
|
+
self.release(self.con, self.expire)
|
|
80
|
+
|
|
81
|
+
def release(self, con, expire):
|
|
82
|
+
if con is None or con.closed or getattr(con, 'broken', False):
|
|
83
|
+
return
|
|
84
|
+
try:
|
|
85
|
+
self.queue.put_nowait((con, expire))
|
|
86
|
+
except queue.Full:
|
|
87
|
+
try:
|
|
88
|
+
con.close()
|
|
89
|
+
except psycopg.Error:
|
|
90
|
+
pass
|
|
91
|
+
|
|
92
|
+
def single_connect(self):
|
|
93
|
+
return psycopg.connect(conninfo=Configs.configs[self.configname]['dsn'])
|