database-wrapper-pgsql 0.2.33__py3-none-any.whl → 0.2.38__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.
@@ -1,7 +1,9 @@
1
+ import asyncio
1
2
  from collections.abc import AsyncIterator, Iterator
2
3
  from contextlib import asynccontextmanager, contextmanager
3
4
  from contextvars import ContextVar
4
5
  from typing import Any, NotRequired, TypedDict, cast
6
+ from urllib.parse import quote
5
7
 
6
8
  from psycopg import AsyncConnection as PgConnectionAsync # Async
7
9
  from psycopg import AsyncCursor as PgCursorAsync
@@ -181,8 +183,11 @@ class PgsqlAsync(DatabaseBackend):
181
183
  """Destructor"""
182
184
 
183
185
  # Just to be sure as async does not have __del__
184
- del self.cursor
185
- del self.connection
186
+ if hasattr(self, "cursor"):
187
+ del self.cursor
188
+
189
+ if hasattr(self, "connection"):
190
+ del self.connection
186
191
 
187
192
  async def open(self) -> None:
188
193
  # Free resources
@@ -378,8 +383,10 @@ class PgsqlWithPooling(DatabaseBackend):
378
383
  self.config["pool_kwargs"] = {}
379
384
 
380
385
  conn_str = (
381
- f"postgresql://{self.config['username']}:{self.config['password']}@{self.config['hostname']}:{self.config['port']}"
382
- f"/{self.config['database']}?connect_timeout={self.connection_timeout}&application_name={self.name}"
386
+ f"postgresql://{quote(self.config['username'])}:{quote(self.config['password'])}"
387
+ f"@{self.config['hostname']}:{self.config['port']}"
388
+ f"/{quote(self.config['database'])}?connect_timeout={self.connection_timeout}"
389
+ f"&application_name={quote(self.name)}"
383
390
  f"&sslmode={self.config['ssl']}"
384
391
  )
385
392
  self.pool = ConnectionPool(
@@ -390,7 +397,10 @@ class PgsqlWithPooling(DatabaseBackend):
390
397
  max_lifetime=20 * 60,
391
398
  max_idle=400,
392
399
  timeout=self.connection_timeout,
393
- reconnect_timeout=0,
400
+ # Validate connections on checkout and keep retrying to refill broken
401
+ # ones, so a transient DB/network stall can't permanently wedge the pool.
402
+ reconnect_timeout=300,
403
+ check=ConnectionPool.check_connection,
394
404
  num_workers=4,
395
405
  connection_class=PgConnectionType,
396
406
  kwargs=self.config["kwargs"],
@@ -424,8 +434,29 @@ class PgsqlWithPooling(DatabaseBackend):
424
434
 
425
435
  # Create new connection
426
436
  res = self.new_connection()
427
- if res:
428
- (self.connection, self.cursor) = res
437
+ if not res:
438
+ raise ConnectionError("Failed to get a connection from the pool")
439
+
440
+ (self.connection, self.cursor) = res
441
+
442
+ def close(self) -> None:
443
+ """Close connection by returning it to the pool"""
444
+ try:
445
+ if self.cursor:
446
+ self.logger.debug("Closing cursor")
447
+ self.cursor.close()
448
+ except Exception as e:
449
+ self.logger.debug(f"Error while closing cursor: {e}")
450
+ finally:
451
+ self.cursor = None
452
+
453
+ if self.connection:
454
+ connection = self.connection
455
+ self.connection = None
456
+ try:
457
+ self.return_connection(connection)
458
+ except Exception as e:
459
+ self.logger.debug(f"Error while returning connection to the pool: {e}")
429
460
 
430
461
  def new_connection(
431
462
  self,
@@ -488,12 +519,14 @@ class PgsqlWithPooling(DatabaseBackend):
488
519
  ) -> tuple[PgConnectionType | None, PgCursorType | None]:
489
520
  """Context manager"""
490
521
 
491
- # Lets set the context var so that it is set even if we fail to get connection
492
- self.context_connection.set(None)
493
-
522
+ # Connections are kept in a per-context stack so that nested
523
+ # context managers each get and return their own connection.
524
+ # A failed connection pushes None to keep push/pop balanced.
494
525
  res = self.new_connection()
526
+ stack = self.context_connection.get() or ()
527
+ self.context_connection.set(stack + (res,))
528
+
495
529
  if res:
496
- self.context_connection.set(res)
497
530
  return res
498
531
 
499
532
  return (
@@ -504,12 +537,12 @@ class PgsqlWithPooling(DatabaseBackend):
504
537
  def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
505
538
  """Context manager"""
506
539
 
507
- test_data = self.context_connection.get()
508
- if test_data:
509
- self.return_connection(test_data[0])
510
-
511
- # Reset context
512
- self.context_connection.set(None)
540
+ stack = self.context_connection.get() or ()
541
+ if stack:
542
+ entry = stack[-1]
543
+ self.context_connection.set(stack[:-1])
544
+ if entry:
545
+ self.return_connection(entry[0])
513
546
 
514
547
  ####################
515
548
  ### Transactions ###
@@ -645,8 +678,10 @@ class PgsqlWithPoolingAsync(DatabaseBackend):
645
678
  self.config["pool_kwargs"] = {}
646
679
 
647
680
  conn_str = (
648
- f"postgresql://{self.config['username']}:{self.config['password']}@{self.config['hostname']}:{self.config['port']}"
649
- f"/{self.config['database']}?connect_timeout={self.connection_timeout}&application_name={self.name}"
681
+ f"postgresql://{quote(self.config['username'])}:{quote(self.config['password'])}"
682
+ f"@{self.config['hostname']}:{self.config['port']}"
683
+ f"/{quote(self.config['database'])}?connect_timeout={self.connection_timeout}"
684
+ f"&application_name={quote(self.name)}"
650
685
  f"&sslmode={self.config['ssl']}"
651
686
  )
652
687
  self.pool_async = AsyncConnectionPool(
@@ -657,7 +692,10 @@ class PgsqlWithPoolingAsync(DatabaseBackend):
657
692
  max_lifetime=20 * 60,
658
693
  max_idle=400,
659
694
  timeout=self.connection_timeout,
660
- reconnect_timeout=0,
695
+ # Validate connections on checkout and keep retrying to refill broken
696
+ # ones, so a transient DB/network stall can't permanently wedge the pool.
697
+ reconnect_timeout=300,
698
+ check=AsyncConnectionPool.check_connection,
661
699
  num_workers=4,
662
700
  connection_class=PgConnectionTypeAsync,
663
701
  kwargs=self.config["kwargs"],
@@ -666,9 +704,14 @@ class PgsqlWithPoolingAsync(DatabaseBackend):
666
704
 
667
705
  def __del__(self) -> None:
668
706
  """Destructor"""
669
- del self.cursor
670
- del self.connection
671
- del self.pool_async
707
+ if hasattr(self, "cursor"):
708
+ del self.cursor
709
+
710
+ if hasattr(self, "connection"):
711
+ del self.connection
712
+
713
+ if hasattr(self, "pool_async"):
714
+ del self.pool_async
672
715
 
673
716
  ##################
674
717
  ### Connection ###
@@ -697,20 +740,29 @@ class PgsqlWithPoolingAsync(DatabaseBackend):
697
740
 
698
741
  # Create new connection
699
742
  res = await self.new_connection()
700
- if res:
701
- (self.connection, self.cursor) = res
743
+ if not res:
744
+ raise ConnectionError("Failed to get a connection from the pool")
745
+
746
+ (self.connection, self.cursor) = res
702
747
 
703
748
  async def close(self) -> None:
704
749
  """Close connection by returning it to the pool"""
705
-
706
- if self.cursor:
707
- self.logger.debug("Closing cursor")
708
- await self.cursor.close()
750
+ try:
751
+ if self.cursor:
752
+ self.logger.debug("Closing cursor")
753
+ await self.cursor.close()
754
+ except Exception as e:
755
+ self.logger.debug(f"Error while closing cursor: {e}")
756
+ finally:
709
757
  self.cursor = None
710
758
 
711
759
  if self.connection:
712
- await self.return_connection(self.connection)
760
+ connection = self.connection
713
761
  self.connection = None
762
+ try:
763
+ await self.return_connection(connection)
764
+ except Exception as e:
765
+ self.logger.debug(f"Error while returning connection to the pool: {e}")
714
766
 
715
767
  async def new_connection(
716
768
  self,
@@ -743,7 +795,9 @@ class PgsqlWithPoolingAsync(DatabaseBackend):
743
795
  await self.pool_async.putconn(connection)
744
796
 
745
797
  self.logger.error(f"Error while getting connection from the pool: {e}")
746
- self.shutdown_requested.wait(self.slow_down_timeout)
798
+ # Event.wait() would block the whole event loop; the loop condition
799
+ # re-checks shutdown_requested after the sleep
800
+ await asyncio.sleep(self.slow_down_timeout)
747
801
  tries += 1
748
802
  if tries >= 3:
749
803
  break
@@ -773,12 +827,14 @@ class PgsqlWithPoolingAsync(DatabaseBackend):
773
827
  ) -> tuple[PgConnectionTypeAsync | None, PgCursorTypeAsync | None]:
774
828
  """Context manager"""
775
829
 
776
- # Lets set the context var so that it is set even if we fail to get connection
777
- self.context_connection_async.set(None)
778
-
830
+ # Connections are kept in a per-context stack so that nested
831
+ # context managers each get and return their own connection.
832
+ # A failed connection pushes None to keep push/pop balanced.
779
833
  res = await self.new_connection()
834
+ stack = self.context_connection_async.get() or ()
835
+ self.context_connection_async.set(stack + (res,))
836
+
780
837
  if res:
781
- self.context_connection_async.set(res)
782
838
  return res
783
839
 
784
840
  return (
@@ -789,12 +845,12 @@ class PgsqlWithPoolingAsync(DatabaseBackend):
789
845
  async def __aexit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
790
846
  """Context manager"""
791
847
 
792
- test_data = self.context_connection_async.get()
793
- if test_data:
794
- await self.return_connection(test_data[0])
795
-
796
- # Reset context
797
- self.context_connection_async.set(None)
848
+ stack = self.context_connection_async.get() or ()
849
+ if stack:
850
+ entry = stack[-1]
851
+ self.context_connection_async.set(stack[:-1])
852
+ if entry:
853
+ await self.return_connection(entry[0])
798
854
 
799
855
  ####################
800
856
  ### Transactions ###
@@ -2,7 +2,7 @@ from typing import Any
2
2
 
3
3
  from psycopg import sql
4
4
 
5
- from database_wrapper import NoParam, OrderByItem
5
+ from database_wrapper import NoParam, OrderByItem, RawSQL
6
6
 
7
7
 
8
8
  class DBWrapperPgsqlMixin:
@@ -72,8 +72,10 @@ class DBWrapperPgsqlMixin:
72
72
 
73
73
  order_list = [
74
74
  sql.SQL("{} {}").format(
75
- sql.Identifier(item[0]),
76
- sql.SQL(item[1] if len(item) > 1 and item[1] is not None else "ASC"),
75
+ # RawSQL keys are trusted expressions; Identifier would quote them as one name
76
+ sql.SQL(item[0]) if isinstance(item[0], RawSQL) else sql.Identifier(item[0]),
77
+ # order_direction (from DBWrapperMixin via MRO) validates against ASC/DESC
78
+ sql.SQL(self.order_direction(item)), # type: ignore[attr-defined]
77
79
  )
78
80
  for item in order_by
79
81
  ]
@@ -1,4 +1,5 @@
1
1
  import psycopg
2
+ from psycopg.rows import dict_row
2
3
 
3
4
  from database_wrapper import ColumnMetaIntrospector, DBIntrospector
4
5
 
@@ -53,7 +54,8 @@ class PostgresIntrospector(DBIntrospector):
53
54
  END AS enum_labels
54
55
  FROM cols;
55
56
  """
56
- with self.conn.cursor() as cur:
57
+ # Explicit row factory - the default psycopg cursor returns tuples
58
+ with self.conn.cursor(row_factory=dict_row) as cur:
57
59
  cur.execute(q, (schema, table))
58
60
  rows = cur.fetchall()
59
61
 
@@ -66,7 +68,7 @@ class PostgresIntrospector(DBIntrospector):
66
68
  is_nullable=bool(row["is_nullable"]),
67
69
  has_default=(row["default_expr"] is not None),
68
70
  default_expr=row["default_expr"],
69
- # enum_labels=list(row["enum_labels"]) if row["enum_labels"] else None,
71
+ enum_labels=list(row["enum_labels"]) if row["enum_labels"] else None,
70
72
  )
71
73
  )
72
74
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: database_wrapper_pgsql
3
- Version: 0.2.33
3
+ Version: 0.2.38
4
4
  Summary: database_wrapper for PostgreSQL database
5
5
  Author-email: Gints Murans <gm@gm.lv>
6
6
  License: GNU General Public License v3.0 (GPL-3.0)
@@ -32,7 +32,7 @@ Classifier: Topic :: Software Development
32
32
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
33
33
  Requires-Python: >=3.8
34
34
  Description-Content-Type: text/markdown
35
- Requires-Dist: database_wrapper==0.2.33
35
+ Requires-Dist: database_wrapper==0.2.38
36
36
  Requires-Dist: psycopg[binary]>=3.2.0
37
37
  Requires-Dist: psycopg[pool]>=3.2.0
38
38
 
@@ -0,0 +1,12 @@
1
+ database_wrapper_pgsql/__init__.py,sha256=p1CkqOmXI61cy3uzpnRtukUG8vQrLfXCFPrwDfOEvFU,1161
2
+ database_wrapper_pgsql/connector.py,sha256=Dr_S0aD1SjfsTuCma1zQocSJSwWKOoePuR0fcEGM8r4,27993
3
+ database_wrapper_pgsql/db_wrapper_pgsql.py,sha256=lrMN9lqfS0JapEfNu2sFeFxifK67eBhZZebU3MpvnRk,1909
4
+ database_wrapper_pgsql/db_wrapper_pgsql_async.py,sha256=cYYyBFWvVG3e24Ik0mJXnbxic9bskqnB-K3hEbJ6pk8,2025
5
+ database_wrapper_pgsql/db_wrapper_pgsql_mixin.py,sha256=pFAG6dX1_fjuDDKk0XSBxmBKwg6_w3KFbmf8M2JRxm4,5692
6
+ database_wrapper_pgsql/pg_introspector.py,sha256=-9_tTxOG7778gxaGuhsxcbCN42mEjr9kG-EAegxsU74,2684
7
+ database_wrapper_pgsql/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ database_wrapper_pgsql/type_mapping.py,sha256=KWIAT78Z6h5DEt8uQNfQP6t5ahBUPuLKgcPfQmIywM4,1625
9
+ database_wrapper_pgsql-0.2.38.dist-info/METADATA,sha256=muIPhFaxfYn0z9kUsINM6tq4OoVGFdBLOehJgeZTawI,3231
10
+ database_wrapper_pgsql-0.2.38.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
11
+ database_wrapper_pgsql-0.2.38.dist-info/top_level.txt,sha256=EQhZLk12wRdsSp-Lo3Jc4cXmNfG8y5EouNv_7OBCSGo,23
12
+ database_wrapper_pgsql-0.2.38.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (82.0.1)
2
+ Generator: setuptools (83.0.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,12 +0,0 @@
1
- database_wrapper_pgsql/__init__.py,sha256=p1CkqOmXI61cy3uzpnRtukUG8vQrLfXCFPrwDfOEvFU,1161
2
- database_wrapper_pgsql/connector.py,sha256=l1Dk35hnSDlGhgdzB4ldrJa6QL83CKn-VgD_R11P2Go,25548
3
- database_wrapper_pgsql/db_wrapper_pgsql.py,sha256=lrMN9lqfS0JapEfNu2sFeFxifK67eBhZZebU3MpvnRk,1909
4
- database_wrapper_pgsql/db_wrapper_pgsql_async.py,sha256=cYYyBFWvVG3e24Ik0mJXnbxic9bskqnB-K3hEbJ6pk8,2025
5
- database_wrapper_pgsql/db_wrapper_pgsql_mixin.py,sha256=m6scMsSCAE7mhU2wV3D_V9hFS52zP1_SFwIiAIVKFKo,5448
6
- database_wrapper_pgsql/pg_introspector.py,sha256=mMIosvQZZNE3ocAF7Wys50gYBjXrT9EaI-xcTWt-UnQ,2557
7
- database_wrapper_pgsql/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
- database_wrapper_pgsql/type_mapping.py,sha256=KWIAT78Z6h5DEt8uQNfQP6t5ahBUPuLKgcPfQmIywM4,1625
9
- database_wrapper_pgsql-0.2.33.dist-info/METADATA,sha256=uu7VML4k0SuHjFdwTCvgZbaahWkO9ZBFhJKQSvBCAEI,3231
10
- database_wrapper_pgsql-0.2.33.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
11
- database_wrapper_pgsql-0.2.33.dist-info/top_level.txt,sha256=EQhZLk12wRdsSp-Lo3Jc4cXmNfG8y5EouNv_7OBCSGo,23
12
- database_wrapper_pgsql-0.2.33.dist-info/RECORD,,