sqlspec 0.4.0__py3-none-any.whl → 0.5.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.

Potentially problematic release.


This version of sqlspec might be problematic. Click here for more details.

sqlspec/_serialization.py CHANGED
@@ -13,7 +13,7 @@ try:
13
13
 
14
14
  except ImportError:
15
15
  try:
16
- from orjson import dumps as _encode_json # pyright: ignore[reportMissingImports]
16
+ from orjson import dumps as _encode_json # pyright: ignore[reportMissingImports,reportUnknownVariableType]
17
17
  from orjson import loads as decode_json # type: ignore[no-redef]
18
18
 
19
19
  def encode_json(data: Any) -> str:
sqlspec/_typing.py CHANGED
@@ -29,7 +29,6 @@ class DataclassProtocol(Protocol):
29
29
  T = TypeVar("T")
30
30
  T_co = TypeVar("T_co", covariant=True)
31
31
 
32
-
33
32
  try:
34
33
  from pydantic import BaseModel, FailFast, TypeAdapter
35
34
 
@@ -110,6 +109,35 @@ except ImportError:
110
109
  UNSET = UnsetType.UNSET # pyright: ignore[reportConstantRedefinition]
111
110
  MSGSPEC_INSTALLED = False # pyright: ignore[reportConstantRedefinition]
112
111
 
112
+ try:
113
+ from litestar.dto.data_structures import DTOData # pyright: ignore[reportUnknownVariableType]
114
+
115
+ LITESTAR_INSTALLED = True
116
+ except ImportError:
117
+
118
+ @runtime_checkable
119
+ class DTOData(Protocol[T]): # type: ignore[no-redef]
120
+ """Placeholder implementation"""
121
+
122
+ __slots__ = ("_backend", "_data_as_builtins")
123
+
124
+ def __init__(self, backend: Any, data_as_builtins: Any) -> None:
125
+ """Placeholder init"""
126
+
127
+ def create_instance(self, **kwargs: Any) -> T:
128
+ """Placeholder implementation"""
129
+ return cast("T", kwargs)
130
+
131
+ def update_instance(self, instance: T, **kwargs: Any) -> T:
132
+ """Placeholder implementation"""
133
+ return cast("T", kwargs)
134
+
135
+ def as_builtins(self) -> Any:
136
+ """Placeholder implementation"""
137
+ return {}
138
+
139
+ LITESTAR_INSTALLED = False # pyright: ignore[reportConstantRedefinition]
140
+
113
141
 
114
142
  class EmptyEnum(Enum):
115
143
  """A sentinel enum used as placeholder."""
@@ -122,10 +150,12 @@ Empty: Final = EmptyEnum.EMPTY
122
150
 
123
151
 
124
152
  __all__ = (
153
+ "LITESTAR_INSTALLED",
125
154
  "MSGSPEC_INSTALLED",
126
155
  "PYDANTIC_INSTALLED",
127
156
  "UNSET",
128
157
  "BaseModel",
158
+ "DTOData",
129
159
  "DataclassProtocol",
130
160
  "Empty",
131
161
  "EmptyEnum",
@@ -2,31 +2,31 @@ from __future__ import annotations
2
2
 
3
3
  from contextlib import contextmanager
4
4
  from dataclasses import dataclass
5
- from typing import TYPE_CHECKING, TypeVar
5
+ from typing import TYPE_CHECKING
6
6
 
7
- from sqlspec.config import GenericDatabaseConfig
7
+ from sqlspec.base import GenericDatabaseConfig, NoPoolConfig
8
8
  from sqlspec.typing import Empty, EmptyType
9
9
 
10
10
  if TYPE_CHECKING:
11
11
  from collections.abc import Generator
12
12
  from typing import Any
13
13
 
14
- from adbc_driver_manager.dbapi import Connection, Cursor
14
+ from adbc_driver_manager.dbapi import Connection
15
15
 
16
16
  __all__ = ("AdbcDatabaseConfig",)
17
17
 
18
- ConnectionT = TypeVar("ConnectionT", bound="Connection")
19
- CursorT = TypeVar("CursorT", bound="Cursor")
20
-
21
18
 
22
19
  @dataclass
23
- class AdbcDatabaseConfig(GenericDatabaseConfig):
20
+ class AdbcDatabaseConfig(NoPoolConfig["Connection"], GenericDatabaseConfig):
24
21
  """Configuration for ADBC connections.
25
22
 
26
23
  This class provides configuration options for ADBC database connections using the
27
24
  ADBC Driver Manager.([1](https://arrow.apache.org/adbc/current/python/api/adbc_driver_manager.html))
28
25
  """
29
26
 
27
+ __supports_connection_pooling = False
28
+ __is_async = False
29
+
30
30
  uri: str | EmptyType = Empty
31
31
  """Database URI"""
32
32
  driver_name: str | EmptyType = Empty
@@ -4,7 +4,7 @@ from contextlib import asynccontextmanager
4
4
  from dataclasses import dataclass
5
5
  from typing import TYPE_CHECKING, Any
6
6
 
7
- from sqlspec.config import GenericDatabaseConfig
7
+ from sqlspec.base import GenericDatabaseConfig, NoPoolConfig
8
8
  from sqlspec.exceptions import ImproperConfigurationError
9
9
  from sqlspec.typing import Empty, EmptyType, dataclass_to_dict
10
10
 
@@ -19,7 +19,7 @@ __all__ = ("AiosqliteConfig",)
19
19
 
20
20
 
21
21
  @dataclass
22
- class AiosqliteConfig(GenericDatabaseConfig):
22
+ class AiosqliteConfig(NoPoolConfig["Connection"], GenericDatabaseConfig):
23
23
  """Configuration for Aiosqlite database connections.
24
24
 
25
25
  This class provides configuration options for Aiosqlite database connections, wrapping all parameters
@@ -4,6 +4,10 @@ from contextlib import asynccontextmanager
4
4
  from dataclasses import dataclass
5
5
  from typing import TYPE_CHECKING, TypeVar
6
6
 
7
+ from asyncmy.connection import Connection
8
+ from asyncmy.pool import Pool
9
+
10
+ from sqlspec.base import DatabaseConfigProtocol, GenericDatabaseConfig, GenericPoolConfig
7
11
  from sqlspec.exceptions import ImproperConfigurationError
8
12
  from sqlspec.typing import Empty, EmptyType, dataclass_to_dict
9
13
 
@@ -11,9 +15,7 @@ if TYPE_CHECKING:
11
15
  from collections.abc import AsyncGenerator
12
16
  from typing import Any
13
17
 
14
- from asyncmy.connection import Connection
15
18
  from asyncmy.cursors import Cursor, DictCursor
16
- from asyncmy.pool import Pool
17
19
 
18
20
  __all__ = (
19
21
  "AsyncMyConfig",
@@ -25,7 +27,7 @@ T = TypeVar("T")
25
27
 
26
28
 
27
29
  @dataclass
28
- class AsyncmyPoolConfig:
30
+ class AsyncmyPoolConfig(GenericPoolConfig):
29
31
  """Configuration for Asyncmy's connection pool.
30
32
 
31
33
  This class provides configuration options for Asyncmy database connection pools.
@@ -104,9 +106,12 @@ class AsyncmyPoolConfig:
104
106
 
105
107
 
106
108
  @dataclass
107
- class AsyncMyConfig:
109
+ class AsyncMyConfig(DatabaseConfigProtocol[Connection, Pool], GenericDatabaseConfig):
108
110
  """Asyncmy Configuration."""
109
111
 
112
+ __is_async__ = True
113
+ __supports_connection_pooling__ = True
114
+
110
115
  pool_config: AsyncmyPoolConfig | None = None
111
116
  """Asyncmy Pool configuration"""
112
117
 
@@ -2,13 +2,16 @@ from __future__ import annotations
2
2
 
3
3
  from contextlib import asynccontextmanager
4
4
  from dataclasses import dataclass
5
- from typing import TYPE_CHECKING, TypeVar
5
+ from typing import TYPE_CHECKING, TypeVar, Union
6
6
 
7
7
  from asyncpg import Record
8
8
  from asyncpg import create_pool as asyncpg_create_pool
9
+ from asyncpg.connection import Connection
10
+ from asyncpg.pool import Pool, PoolConnectionProxy
11
+ from typing_extensions import TypeAlias
9
12
 
10
13
  from sqlspec._serialization import decode_json, encode_json
11
- from sqlspec.config import GenericDatabaseConfig, GenericPoolConfig
14
+ from sqlspec.base import DatabaseConfigProtocol, GenericDatabaseConfig, GenericPoolConfig
12
15
  from sqlspec.exceptions import ImproperConfigurationError
13
16
  from sqlspec.typing import Empty, EmptyType, dataclass_to_dict
14
17
 
@@ -17,8 +20,6 @@ if TYPE_CHECKING:
17
20
  from collections.abc import AsyncGenerator, Awaitable, Callable, Coroutine
18
21
  from typing import Any
19
22
 
20
- from asyncpg.connection import Connection
21
- from asyncpg.pool import Pool, PoolConnectionProxy
22
23
 
23
24
  __all__ = (
24
25
  "AsyncPgConfig",
@@ -28,6 +29,8 @@ __all__ = (
28
29
 
29
30
  T = TypeVar("T")
30
31
 
32
+ PgConnection: TypeAlias = Union[Connection, PoolConnectionProxy]
33
+
31
34
 
32
35
  @dataclass
33
36
  class AsyncPgPoolConfig(GenericPoolConfig):
@@ -70,9 +73,12 @@ class AsyncPgPoolConfig(GenericPoolConfig):
70
73
 
71
74
 
72
75
  @dataclass
73
- class AsyncPgConfig(GenericDatabaseConfig):
76
+ class AsyncPgConfig(DatabaseConfigProtocol[PgConnection, Pool], GenericDatabaseConfig):
74
77
  """Asyncpg Configuration."""
75
78
 
79
+ __is_async__ = True
80
+ __supports_connection_pooling__ = True
81
+
76
82
  pool_config: AsyncPgPoolConfig | None = None
77
83
  """Asyncpg Pool configuration"""
78
84
  json_deserializer: Callable[[str], Any] = decode_json
@@ -132,9 +138,7 @@ class AsyncPgConfig(GenericDatabaseConfig):
132
138
  return self.create_pool()
133
139
 
134
140
  @asynccontextmanager
135
- async def provide_connection(
136
- self, *args: Any, **kwargs: Any
137
- ) -> AsyncGenerator[Connection | PoolConnectionProxy, None]:
141
+ async def provide_connection(self, *args: Any, **kwargs: Any) -> AsyncGenerator[PoolConnectionProxy, None]:
138
142
  """Create a connection instance.
139
143
 
140
144
  Returns:
@@ -0,0 +1,3 @@
1
+ from sqlspec.adapters.duckdb.config import DuckDBConfig
2
+
3
+ __all__ = ("DuckDBConfig",)
@@ -4,14 +4,15 @@ from contextlib import contextmanager
4
4
  from dataclasses import dataclass
5
5
  from typing import TYPE_CHECKING, Any, cast
6
6
 
7
- from sqlspec.config import GenericDatabaseConfig
7
+ from duckdb import DuckDBPyConnection
8
+
9
+ from sqlspec.base import GenericDatabaseConfig, NoPoolConfig
8
10
  from sqlspec.exceptions import ImproperConfigurationError
9
11
  from sqlspec.typing import Empty, EmptyType, dataclass_to_dict
10
12
 
11
13
  if TYPE_CHECKING:
12
14
  from collections.abc import Generator, Sequence
13
15
 
14
- from duckdb import DuckDBPyConnection
15
16
 
16
17
  __all__ = ("DuckDBConfig", "ExtensionConfig")
17
18
 
@@ -23,21 +24,21 @@ class ExtensionConfig:
23
24
  This class provides configuration options for DuckDB extensions, including installation
24
25
  and post-install configuration settings.
25
26
 
26
- Args:
27
- name: The name of the extension to install
28
- config: Optional configuration settings to apply after installation
29
- force_install: Whether to force reinstall if already present
30
- repository: Optional repository name to install from
31
- repository_url: Optional repository URL to install from
32
- version: Optional version of the extension to install
27
+ For details see: https://duckdb.org/docs/extensions/overview
33
28
  """
34
29
 
35
30
  name: str
31
+ """The name of the extension to install"""
36
32
  config: dict[str, Any] | None = None
33
+ """Optional configuration settings to apply after installation"""
37
34
  force_install: bool = False
35
+ """Whether to force reinstall if already present"""
38
36
  repository: str | None = None
37
+ """Optional repository name to install from"""
39
38
  repository_url: str | None = None
39
+ """Optional repository URL to install from"""
40
40
  version: str | None = None
41
+ """Optional version of the extension to install"""
41
42
 
42
43
  @classmethod
43
44
  def from_dict(cls, name: str, config: dict[str, Any] | bool | None = None) -> ExtensionConfig:
@@ -65,7 +66,7 @@ class ExtensionConfig:
65
66
 
66
67
 
67
68
  @dataclass
68
- class DuckDBConfig(GenericDatabaseConfig):
69
+ class DuckDBConfig(NoPoolConfig[DuckDBPyConnection], GenericDatabaseConfig):
69
70
  """Configuration for DuckDB database connections.
70
71
 
71
72
  This class provides configuration options for DuckDB database connections, wrapping all parameters
@@ -114,13 +115,13 @@ class DuckDBConfig(GenericDatabaseConfig):
114
115
  msg = "When configuring extensions in the 'config' dictionary, the value must be a dictionary or sequence of extension names"
115
116
  raise ImproperConfigurationError(msg)
116
117
  if not isinstance(_e, dict):
117
- _e = {str(ext): {"force_install": False} for ext in _e}
118
+ _e = {str(ext): {"force_install": False} for ext in _e} # pyright: ignore[reportUnknownVariableType,reportUnknownArgumentType]
118
119
 
119
- if len(set(_e.keys()).intersection({ext.name for ext in self.extensions})) > 0:
120
+ if len(set(_e.keys()).intersection({ext.name for ext in self.extensions})) > 0: # pyright: ignore[ reportUnknownArgumentType]
120
121
  msg = "Configuring the same extension in both 'extensions' and as a key in 'config['extensions']' is not allowed"
121
122
  raise ImproperConfigurationError(msg)
122
123
 
123
- self.extensions.extend([ExtensionConfig.from_dict(name, ext_config) for name, ext_config in _e.items()])
124
+ self.extensions.extend([ExtensionConfig.from_dict(name, ext_config) for name, ext_config in _e.items()]) # pyright: ignore[reportUnknownArgumentType,reportUnknownVariableType]
124
125
 
125
126
  def _configure_extensions(self, connection: DuckDBPyConnection) -> None:
126
127
  """Configure extensions for the connection.
@@ -177,7 +178,7 @@ class DuckDBConfig(GenericDatabaseConfig):
177
178
  import duckdb
178
179
 
179
180
  try:
180
- connection = duckdb.connect(**self.connection_config_dict)
181
+ connection = duckdb.connect(**self.connection_config_dict) # pyright: ignore[reportUnknownMemberType]
181
182
  self._configure_extensions(connection)
182
183
  return connection
183
184
  except Exception as e:
@@ -1,4 +1,4 @@
1
- from .config import (
1
+ from sqlspec.adapters.oracledb.config import (
2
2
  OracleAsyncDatabaseConfig,
3
3
  OracleAsyncPoolConfig,
4
4
  OracleSyncDatabaseConfig,
@@ -26,14 +26,17 @@ __all__ = (
26
26
 
27
27
 
28
28
  @dataclass
29
- class OracleAsyncPoolConfig(OracleGenericPoolConfig[AsyncConnectionPool, AsyncConnection]):
29
+ class OracleAsyncPoolConfig(OracleGenericPoolConfig[AsyncConnection, AsyncConnectionPool]):
30
30
  """Async Oracle Pool Config"""
31
31
 
32
32
 
33
33
  @dataclass
34
- class OracleAsyncDatabaseConfig(OracleGenericDatabaseConfig[AsyncConnectionPool, AsyncConnection]):
34
+ class OracleAsyncDatabaseConfig(OracleGenericDatabaseConfig[AsyncConnection, AsyncConnectionPool]):
35
35
  """Async Oracle database Configuration."""
36
36
 
37
+ __is_async__ = True
38
+ __supports_connection_pooling__ = True
39
+
37
40
  pool_config: OracleAsyncPoolConfig | None = None
38
41
  """Oracle Pool configuration"""
39
42
  pool_instance: AsyncConnectionPool | None = None
@@ -70,7 +73,7 @@ class OracleAsyncDatabaseConfig(OracleGenericDatabaseConfig[AsyncConnectionPool,
70
73
 
71
74
  pool_config = self.pool_config_dict
72
75
  self.pool_instance = oracledb_create_pool(**pool_config)
73
- if self.pool_instance is None:
76
+ if self.pool_instance is None: # pyright: ignore[reportUnnecessaryComparison]
74
77
  msg = "Could not configure the 'pool_instance'. Please check your configuration."
75
78
  raise ImproperConfigurationError(msg)
76
79
  return self.pool_instance
@@ -5,7 +5,7 @@ from typing import TYPE_CHECKING, Generic, TypeVar
5
5
 
6
6
  from oracledb import ConnectionPool
7
7
 
8
- from sqlspec.config import GenericDatabaseConfig, GenericPoolConfig
8
+ from sqlspec.base import DatabaseConfigProtocol, GenericDatabaseConfig, GenericPoolConfig
9
9
  from sqlspec.typing import Empty
10
10
 
11
11
  if TYPE_CHECKING:
@@ -32,7 +32,7 @@ PoolT = TypeVar("PoolT", bound="ConnectionPool | AsyncConnectionPool")
32
32
 
33
33
 
34
34
  @dataclass
35
- class OracleGenericPoolConfig(Generic[PoolT, ConnectionT], GenericPoolConfig):
35
+ class OracleGenericPoolConfig(Generic[ConnectionT, PoolT], GenericPoolConfig):
36
36
  """Configuration for Oracle database connection pools.
37
37
 
38
38
  This class provides configuration options for both synchronous and asynchronous Oracle
@@ -58,7 +58,7 @@ class OracleGenericPoolConfig(Generic[PoolT, ConnectionT], GenericPoolConfig):
58
58
  """New password for password change operations"""
59
59
  wallet_password: str | EmptyType = Empty
60
60
  """Password for accessing Oracle Wallet"""
61
- access_token: str | tuple | Callable | EmptyType = Empty
61
+ access_token: str | tuple[str, ...] | Callable[[], str] | EmptyType = Empty
62
62
  """Token for token-based authentication"""
63
63
  host: str | EmptyType = Empty
64
64
  """Database server hostname"""
@@ -112,11 +112,11 @@ class OracleGenericPoolConfig(Generic[PoolT, ConnectionT], GenericPoolConfig):
112
112
  """If True, allows connections with different tags"""
113
113
  config_dir: str | EmptyType = Empty
114
114
  """Directory containing Oracle configuration files"""
115
- appcontext: list | EmptyType = Empty
115
+ appcontext: list[str] | EmptyType = Empty
116
116
  """Application context list"""
117
- shardingkey: list | EmptyType = Empty
117
+ shardingkey: list[str] | EmptyType = Empty
118
118
  """Sharding key list"""
119
- supershardingkey: list | EmptyType = Empty
119
+ supershardingkey: list[str] | EmptyType = Empty
120
120
  """Super sharding key list"""
121
121
  debug_jdwp: str | EmptyType = Empty
122
122
  """JDWP debugging string"""
@@ -137,7 +137,7 @@ class OracleGenericPoolConfig(Generic[PoolT, ConnectionT], GenericPoolConfig):
137
137
 
138
138
 
139
139
  @dataclass
140
- class OracleGenericDatabaseConfig(Generic[PoolT, ConnectionT], GenericDatabaseConfig):
140
+ class OracleGenericDatabaseConfig(DatabaseConfigProtocol[ConnectionT, PoolT], GenericDatabaseConfig):
141
141
  """Oracle database Configuration.
142
142
 
143
143
  This class provides the base configuration for Oracle database connections, extending
@@ -26,14 +26,17 @@ __all__ = (
26
26
 
27
27
 
28
28
  @dataclass
29
- class OracleSyncPoolConfig(OracleGenericPoolConfig[ConnectionPool, Connection]):
29
+ class OracleSyncPoolConfig(OracleGenericPoolConfig[Connection, ConnectionPool]):
30
30
  """Sync Oracle Pool Config"""
31
31
 
32
32
 
33
33
  @dataclass
34
- class OracleSyncDatabaseConfig(OracleGenericDatabaseConfig[ConnectionPool, Connection]):
34
+ class OracleSyncDatabaseConfig(OracleGenericDatabaseConfig[Connection, ConnectionPool]):
35
35
  """Oracle database Configuration."""
36
36
 
37
+ __is_async__ = False
38
+ __supports_connection_pooling__ = True
39
+
37
40
  pool_config: OracleSyncPoolConfig | None = None
38
41
  """Oracle Pool configuration"""
39
42
  pool_instance: ConnectionPool | None = None
@@ -70,7 +73,7 @@ class OracleSyncDatabaseConfig(OracleGenericDatabaseConfig[ConnectionPool, Conne
70
73
 
71
74
  pool_config = self.pool_config_dict
72
75
  self.pool_instance = oracledb_create_pool(**pool_config)
73
- if self.pool_instance is None:
76
+ if self.pool_instance is None: # pyright: ignore[reportUnnecessaryComparison]
74
77
  msg = "Could not configure the 'pool_instance'. Please check your configuration."
75
78
  raise ImproperConfigurationError(msg)
76
79
  return self.pool_instance
@@ -91,5 +94,5 @@ class OracleSyncDatabaseConfig(OracleGenericDatabaseConfig[ConnectionPool, Conne
91
94
  A connection instance.
92
95
  """
93
96
  db_pool = self.provide_pool(*args, **kwargs)
94
- with db_pool.acquire() as connection:
97
+ with db_pool.acquire() as connection: # pyright: ignore[reportUnknownMemberType]
95
98
  yield connection
@@ -1,5 +1,5 @@
1
- from ._async import PsycoPgAsyncDatabaseConfig, PsycoPgAsyncPoolConfig
2
- from ._sync import PsycoPgSyncDatabaseConfig, PsycoPgSyncPoolConfig
1
+ from sqlspec.adapters.psycopg.config._async import PsycoPgAsyncDatabaseConfig, PsycoPgAsyncPoolConfig
2
+ from sqlspec.adapters.psycopg.config._sync import PsycoPgSyncDatabaseConfig, PsycoPgSyncPoolConfig
3
3
 
4
4
  __all__ = (
5
5
  "PsycoPgAsyncDatabaseConfig",
@@ -26,14 +26,17 @@ __all__ = (
26
26
 
27
27
 
28
28
  @dataclass
29
- class PsycoPgAsyncPoolConfig(PsycoPgGenericPoolConfig[AsyncConnectionPool, AsyncConnection]):
29
+ class PsycoPgAsyncPoolConfig(PsycoPgGenericPoolConfig[AsyncConnection, AsyncConnectionPool]):
30
30
  """Async Psycopg Pool Config"""
31
31
 
32
32
 
33
33
  @dataclass
34
- class PsycoPgAsyncDatabaseConfig(PsycoPgGenericDatabaseConfig[AsyncConnectionPool, AsyncConnection]):
34
+ class PsycoPgAsyncDatabaseConfig(PsycoPgGenericDatabaseConfig[AsyncConnection, AsyncConnectionPool]):
35
35
  """Async Psycopg database Configuration."""
36
36
 
37
+ __is_async__ = True
38
+ __supports_connection_pooling__ = True
39
+
37
40
  pool_config: PsycoPgAsyncPoolConfig | None = None
38
41
  """Psycopg Pool configuration"""
39
42
  pool_instance: AsyncConnectionPool | None = None
@@ -58,7 +61,7 @@ class PsycoPgAsyncDatabaseConfig(PsycoPgGenericDatabaseConfig[AsyncConnectionPoo
58
61
 
59
62
  pool_config = self.pool_config_dict
60
63
  self.pool_instance = AsyncConnectionPool(**pool_config)
61
- if self.pool_instance is None:
64
+ if self.pool_instance is None: # pyright: ignore[reportUnnecessaryComparison]
62
65
  msg = "Could not configure the 'pool_instance'. Please check your configuration." # type: ignore[unreachable]
63
66
  raise ImproperConfigurationError(msg)
64
67
  return self.pool_instance
@@ -3,7 +3,7 @@ from __future__ import annotations
3
3
  from dataclasses import dataclass
4
4
  from typing import TYPE_CHECKING, Generic, TypeVar
5
5
 
6
- from sqlspec.config import GenericDatabaseConfig, GenericPoolConfig
6
+ from sqlspec.base import DatabaseConfigProtocol, GenericDatabaseConfig, GenericPoolConfig
7
7
  from sqlspec.typing import Empty
8
8
 
9
9
  if TYPE_CHECKING:
@@ -27,7 +27,7 @@ PoolT = TypeVar("PoolT", bound="ConnectionPool | AsyncConnectionPool")
27
27
 
28
28
 
29
29
  @dataclass
30
- class PsycoPgGenericPoolConfig(Generic[PoolT, ConnectionT], GenericPoolConfig):
30
+ class PsycoPgGenericPoolConfig(Generic[ConnectionT, PoolT], GenericPoolConfig):
31
31
  """Configuration for Psycopg connection pools.
32
32
 
33
33
  This class provides configuration options for both synchronous and asynchronous Psycopg
@@ -62,7 +62,7 @@ class PsycoPgGenericPoolConfig(Generic[PoolT, ConnectionT], GenericPoolConfig):
62
62
 
63
63
 
64
64
  @dataclass
65
- class PsycoPgGenericDatabaseConfig(Generic[PoolT, ConnectionT], GenericDatabaseConfig):
65
+ class PsycoPgGenericDatabaseConfig(DatabaseConfigProtocol[ConnectionT, PoolT], GenericDatabaseConfig):
66
66
  """Psycopg database Configuration.
67
67
 
68
68
  This class provides the base configuration for Psycopg database connections, extending
@@ -26,14 +26,17 @@ __all__ = (
26
26
 
27
27
 
28
28
  @dataclass
29
- class PsycoPgSyncPoolConfig(PsycoPgGenericPoolConfig[ConnectionPool, Connection]):
29
+ class PsycoPgSyncPoolConfig(PsycoPgGenericPoolConfig[Connection, ConnectionPool]):
30
30
  """Sync Psycopg Pool Config"""
31
31
 
32
32
 
33
33
  @dataclass
34
- class PsycoPgSyncDatabaseConfig(PsycoPgGenericDatabaseConfig[ConnectionPool, Connection]):
34
+ class PsycoPgSyncDatabaseConfig(PsycoPgGenericDatabaseConfig[Connection, ConnectionPool]):
35
35
  """Sync Psycopg database Configuration."""
36
36
 
37
+ __is_async__ = False
38
+ __supports_connection_pooling__ = True
39
+
37
40
  pool_config: PsycoPgSyncPoolConfig | None = None
38
41
  """Psycopg Pool configuration"""
39
42
  pool_instance: ConnectionPool | None = None
@@ -58,7 +61,7 @@ class PsycoPgSyncDatabaseConfig(PsycoPgGenericDatabaseConfig[ConnectionPool, Con
58
61
 
59
62
  pool_config = self.pool_config_dict
60
63
  self.pool_instance = ConnectionPool(**pool_config)
61
- if self.pool_instance is None:
64
+ if self.pool_instance is None: # pyright: ignore[reportUnnecessaryComparison]
62
65
  msg = "Could not configure the 'pool_instance'. Please check your configuration." # type: ignore[unreachable]
63
66
  raise ImproperConfigurationError(msg)
64
67
  return self.pool_instance
@@ -4,7 +4,7 @@ from contextlib import contextmanager
4
4
  from dataclasses import dataclass
5
5
  from typing import TYPE_CHECKING, Any, Literal
6
6
 
7
- from sqlspec.config import GenericDatabaseConfig
7
+ from sqlspec.base import GenericDatabaseConfig, NoPoolConfig
8
8
  from sqlspec.exceptions import ImproperConfigurationError
9
9
  from sqlspec.typing import Empty, EmptyType, dataclass_to_dict
10
10
 
@@ -16,7 +16,7 @@ __all__ = ("SqliteConfig",)
16
16
 
17
17
 
18
18
  @dataclass
19
- class SqliteConfig(GenericDatabaseConfig):
19
+ class SqliteConfig(NoPoolConfig["Connection"], GenericDatabaseConfig):
20
20
  """Configuration for SQLite database connections.
21
21
 
22
22
  This class provides configuration options for SQLite database connections, wrapping all parameters
@@ -25,7 +25,7 @@ class SqliteConfig(GenericDatabaseConfig):
25
25
  For details see: https://docs.python.org/3/library/sqlite3.html#sqlite3.connect
26
26
  """
27
27
 
28
- database: str
28
+ database: str = ":memory:"
29
29
  """The path to the database file to be opened. Pass ":memory:" to open a connection to a database that resides in RAM instead of on disk."""
30
30
 
31
31
  timeout: float | EmptyType = Empty
sqlspec/base.py ADDED
@@ -0,0 +1,87 @@
1
+ from abc import ABC, abstractmethod
2
+ from collections.abc import AsyncGenerator, Awaitable, Generator
3
+ from contextlib import AbstractAsyncContextManager, AbstractContextManager
4
+ from dataclasses import dataclass
5
+ from typing import Any, ClassVar, Generic, TypeVar, Union
6
+
7
+ __all__ = (
8
+ "DatabaseConfigProtocol",
9
+ "GenericPoolConfig",
10
+ "NoPoolConfig",
11
+ )
12
+
13
+ ConnectionT = TypeVar("ConnectionT")
14
+ PoolT = TypeVar("PoolT")
15
+
16
+
17
+ @dataclass
18
+ class DatabaseConfigProtocol(Generic[ConnectionT, PoolT], ABC):
19
+ """Protocol defining the interface for database configurations."""
20
+
21
+ __is_async__: ClassVar[bool] = False
22
+ __supports_connection_pooling__: ClassVar[bool] = False
23
+
24
+ @abstractmethod
25
+ def create_connection(self) -> Union[ConnectionT, Awaitable[ConnectionT]]:
26
+ """Create and return a new database connection."""
27
+ raise NotImplementedError
28
+
29
+ @abstractmethod
30
+ def provide_connection(
31
+ self, *args: Any, **kwargs: Any
32
+ ) -> Union[
33
+ Generator[ConnectionT, None, None],
34
+ AsyncGenerator[ConnectionT, None],
35
+ AbstractContextManager[ConnectionT],
36
+ AbstractAsyncContextManager[ConnectionT],
37
+ ]:
38
+ """Provide a database connection context manager."""
39
+ raise NotImplementedError
40
+
41
+ @property
42
+ @abstractmethod
43
+ def connection_config_dict(self) -> dict[str, Any]:
44
+ """Return the connection configuration as a dict."""
45
+ raise NotImplementedError
46
+
47
+ @abstractmethod
48
+ def create_pool(self) -> Union[PoolT, Awaitable[PoolT]]:
49
+ """Create and return connection pool."""
50
+ raise NotImplementedError
51
+
52
+ @abstractmethod
53
+ def provide_pool(
54
+ self, *args: Any, **kwargs: Any
55
+ ) -> Union[PoolT, Awaitable[PoolT], AbstractContextManager[PoolT], AbstractAsyncContextManager[PoolT]]:
56
+ """Provide pool instance."""
57
+ raise NotImplementedError
58
+
59
+ @property
60
+ def is_async(self) -> bool:
61
+ """Return whether the configuration is for an async database."""
62
+ return self.__is_async__
63
+
64
+ @property
65
+ def support_connection_pooling(self) -> bool:
66
+ """Return whether the configuration supports connection pooling."""
67
+ return self.__supports_connection_pooling__
68
+
69
+
70
+ class NoPoolConfig(DatabaseConfigProtocol[ConnectionT, None]):
71
+ """Base class for database configurations that do not implement a pool."""
72
+
73
+ def create_pool(self) -> None:
74
+ """This database backend has not implemented the pooling configurations."""
75
+
76
+ def provide_pool(self, *args: Any, **kwargs: Any) -> None:
77
+ """This database backend has not implemented the pooling configurations."""
78
+
79
+
80
+ @dataclass
81
+ class GenericPoolConfig:
82
+ """Generic Database Pool Configuration."""
83
+
84
+
85
+ @dataclass
86
+ class GenericDatabaseConfig:
87
+ """Generic Database Configuration."""
sqlspec/filters.py CHANGED
@@ -25,12 +25,13 @@ __all__ = (
25
25
  )
26
26
 
27
27
  T = TypeVar("T")
28
+ StatementT = TypeVar("StatementT", bound="str")
28
29
 
29
30
 
30
31
  class StatementFilter(Protocol):
31
32
  """Protocol for filters that can be appended to a statement."""
32
33
 
33
- def append_to_statement(self, statement: str) -> str:
34
+ def append_to_statement(self, statement: StatementT) -> StatementT:
34
35
  """Append the filter to the statement."""
35
36
  return statement
36
37