sqlalchemy-firebird-async 0.1.0__py2.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.
File without changes
@@ -0,0 +1,115 @@
1
+ import asyncio
2
+ from functools import partial
3
+
4
+ from sqlalchemy.util.concurrency import await_only
5
+
6
+
7
+ class AsyncCursor:
8
+ def __init__(self, sync_cursor, loop):
9
+ self._sync_cursor = sync_cursor
10
+ self._loop = loop
11
+
12
+ def execute(self, operation, parameters=None):
13
+ if parameters is None:
14
+ func = partial(self._sync_cursor.execute, operation)
15
+ else:
16
+ func = partial(self._sync_cursor.execute, operation, parameters)
17
+ await_only(self._loop.run_in_executor(None, func))
18
+ return self
19
+
20
+ def executemany(self, operation, seq_of_parameters):
21
+ func = partial(self._sync_cursor.executemany, operation, seq_of_parameters)
22
+ await_only(self._loop.run_in_executor(None, func))
23
+ return self
24
+
25
+ def fetchone(self):
26
+ return await_only(self._loop.run_in_executor(None, self._sync_cursor.fetchone))
27
+
28
+ def fetchmany(self, size=None):
29
+ if size is None:
30
+ return await_only(self._loop.run_in_executor(None, self._sync_cursor.fetchmany))
31
+ func = partial(self._sync_cursor.fetchmany, size)
32
+ return await_only(self._loop.run_in_executor(None, func))
33
+
34
+ def fetchall(self):
35
+ return await_only(self._loop.run_in_executor(None, self._sync_cursor.fetchall))
36
+
37
+ def close(self):
38
+ return await_only(self._loop.run_in_executor(None, self._sync_cursor.close))
39
+
40
+ def __getattr__(self, name):
41
+ return getattr(self._sync_cursor, name)
42
+
43
+
44
+ class AsyncConnection:
45
+ def __init__(self, sync_connection, loop):
46
+ self._sync_connection = sync_connection
47
+ self._loop = loop
48
+
49
+ def cursor(self):
50
+ return AsyncCursor(self._sync_connection.cursor(), self._loop)
51
+
52
+ def commit(self):
53
+ await_only(self._loop.run_in_executor(None, self._sync_connection.commit))
54
+
55
+ def rollback(self):
56
+ await_only(self._loop.run_in_executor(None, self._sync_connection.rollback))
57
+
58
+ def close(self):
59
+ await_only(self._loop.run_in_executor(None, self._sync_connection.close))
60
+
61
+ def __getattr__(self, name):
62
+ return getattr(self._sync_connection, name)
63
+
64
+
65
+ class AsyncDBAPI:
66
+ def __init__(self, sync_dbapi):
67
+ self._sync_dbapi = sync_dbapi
68
+ self.paramstyle = getattr(sync_dbapi, "paramstyle", "qmark")
69
+ self.apilevel = getattr(sync_dbapi, "apilevel", "2.0")
70
+ self.threadsafety = getattr(sync_dbapi, "threadsafety", 0)
71
+ for attr in (
72
+ "Warning",
73
+ "Error",
74
+ "InterfaceError",
75
+ "DatabaseError",
76
+ "DataError",
77
+ "OperationalError",
78
+ "IntegrityError",
79
+ "InternalError",
80
+ "ProgrammingError",
81
+ "NotSupportedError",
82
+ ):
83
+ if hasattr(sync_dbapi, attr):
84
+ setattr(self, attr, getattr(sync_dbapi, attr))
85
+
86
+ def connect(self, *args, **kwargs):
87
+ async_creator_fn = kwargs.pop("async_creator_fn", None)
88
+ loop = asyncio.get_running_loop()
89
+ if async_creator_fn is not None:
90
+ sync_conn = await_only(async_creator_fn(*args, **kwargs))
91
+ else:
92
+ func = partial(self._sync_dbapi.connect, *args, **kwargs)
93
+ sync_conn = await_only(loop.run_in_executor(None, func))
94
+ return AsyncConnection(sync_conn, loop)
95
+
96
+ from sqlalchemy.pool import AsyncAdaptedQueuePool
97
+ import sqlalchemy_firebird.fdb as fdb
98
+
99
+
100
+ class AsyncFDBDialect(fdb.FBDialect_fdb):
101
+ name = "firebird.fdb_async"
102
+ driver = "fdb_async"
103
+ is_async = True
104
+ supports_statement_cache = False
105
+ poolclass = AsyncAdaptedQueuePool
106
+
107
+ @classmethod
108
+ def import_dbapi(cls):
109
+ import fdb as sync_fdb
110
+
111
+ return AsyncDBAPI(sync_fdb)
112
+
113
+ @classmethod
114
+ def dbapi(cls):
115
+ return cls.import_dbapi()
@@ -0,0 +1,184 @@
1
+ import asyncio
2
+
3
+ from sqlalchemy import util
4
+ from sqlalchemy.pool import AsyncAdaptedQueuePool
5
+ from sqlalchemy.util.concurrency import await_only
6
+
7
+ import firebirdsql
8
+ import firebirdsql.aio as aio
9
+ import sqlalchemy_firebird.fdb as fdb
10
+
11
+
12
+ def _await_if_needed(value):
13
+ if asyncio.iscoroutine(value):
14
+ try:
15
+ return await_only(value)
16
+ except StopAsyncIteration:
17
+ return None
18
+ return value
19
+
20
+
21
+ class AsyncPyfbCursor:
22
+ def __init__(self, async_cursor):
23
+ self._async_cursor = async_cursor
24
+
25
+ def execute(self, operation, parameters=None):
26
+ if parameters is None:
27
+ _await_if_needed(self._async_cursor.execute(operation))
28
+ else:
29
+ _await_if_needed(self._async_cursor.execute(operation, parameters))
30
+ return self
31
+
32
+ def executemany(self, operation, seq_of_parameters):
33
+ _await_if_needed(self._async_cursor.executemany(operation, seq_of_parameters))
34
+ return self
35
+
36
+ def fetchone(self):
37
+ return _await_if_needed(self._async_cursor.fetchone())
38
+
39
+ def fetchmany(self, size=None):
40
+ # firebirdsql fetchmany signature is fetchmany(self, size=None)
41
+ # but if size is passed it must be used.
42
+ return _await_if_needed(self._async_cursor.fetchmany(size))
43
+
44
+ def fetchall(self):
45
+ return _await_if_needed(self._async_cursor.fetchall())
46
+
47
+ def close(self):
48
+ return _await_if_needed(self._async_cursor.close())
49
+
50
+ async def _async_soft_close(self):
51
+ # SQLAlchemy 2.0 calls this.
52
+ pass
53
+
54
+ def __getattr__(self, name):
55
+ return getattr(self._async_cursor, name)
56
+
57
+
58
+ class AsyncPyfbConnection:
59
+ def __init__(self, async_connection):
60
+ self._async_connection = async_connection
61
+
62
+ def cursor(self):
63
+ return AsyncPyfbCursor(self._async_connection.cursor())
64
+
65
+ def commit(self):
66
+ _await_if_needed(self._async_connection.commit())
67
+
68
+ def rollback(self):
69
+ _await_if_needed(self._async_connection.rollback())
70
+
71
+ def close(self):
72
+ try:
73
+ return _await_if_needed(self._async_connection.close())
74
+ except BlockingIOError:
75
+ sock = getattr(self._async_connection, "sock", None)
76
+ raw_sock = getattr(sock, "_sock", None)
77
+ if raw_sock is not None:
78
+ try:
79
+ raw_sock.setblocking(True)
80
+ except Exception:
81
+ pass
82
+ try:
83
+ return self._async_connection.close()
84
+ except Exception:
85
+ if raw_sock is not None:
86
+ try:
87
+ raw_sock.close()
88
+ except Exception:
89
+ pass
90
+ return None
91
+
92
+ def __getattr__(self, name):
93
+ return getattr(self._async_connection, name)
94
+
95
+
96
+ class AsyncPyfbDBAPI:
97
+ def __init__(self):
98
+ self.paramstyle = getattr(firebirdsql, "paramstyle", "qmark")
99
+ self.apilevel = getattr(firebirdsql, "apilevel", "2.0")
100
+ self.threadsafety = getattr(firebirdsql, "threadsafety", 0)
101
+ for attr in (
102
+ "Warning",
103
+ "Error",
104
+ "InterfaceError",
105
+ "DatabaseError",
106
+ "DataError",
107
+ "OperationalError",
108
+ "IntegrityError",
109
+ "InternalError",
110
+ "ProgrammingError",
111
+ "NotSupportedError",
112
+ ):
113
+ if hasattr(firebirdsql, attr):
114
+ setattr(self, attr, getattr(firebirdsql, attr))
115
+
116
+ def connect(self, *args, **kwargs):
117
+ async_creator_fn = kwargs.pop("async_creator_fn", None)
118
+ if async_creator_fn is None:
119
+ async_creator_fn = aio.connect
120
+ async_connection = await_only(async_creator_fn(*args, **kwargs))
121
+ return AsyncPyfbConnection(async_connection)
122
+
123
+ def Binary(self, value):
124
+ return firebirdsql.Binary(value)
125
+
126
+
127
+ class AsyncFirebirdSQLDialect(fdb.FBDialect_fdb):
128
+ name = "firebird.firebirdsql_async"
129
+ driver = "firebirdsql_async"
130
+ is_async = True
131
+ supports_statement_cache = False
132
+ poolclass = AsyncAdaptedQueuePool
133
+
134
+ @classmethod
135
+ def import_dbapi(cls):
136
+ return AsyncPyfbDBAPI()
137
+
138
+ @classmethod
139
+ def dbapi(cls):
140
+ return cls.import_dbapi()
141
+
142
+ def create_connect_args(self, url):
143
+ opts = url.translate_connect_args(username="user")
144
+ opts.update(url.query)
145
+ util.coerce_kw_type(opts, "port", int)
146
+ return ([], opts)
147
+
148
+ def _get_server_version_info(self, connection):
149
+ try:
150
+ # We must use exec_driver_sql and await the result because scalar()
151
+ # on async connection returns a coroutine.
152
+ # But wait, 'connection' passed here is likely an AsyncAdapt_dbapi_connection
153
+ # wrapper which mimics sync interface but executes via greenlet_spawn?
154
+ # Or is it a raw connection?
155
+ # In asyncio dialect, _get_server_version_info is called in a sync context.
156
+
157
+ # Let's try standard way, but safe:
158
+ res = connection.exec_driver_sql(
159
+ "select rdb$get_context('SYSTEM','ENGINE_VERSION') from rdb$database"
160
+ )
161
+ # res.scalar() is a coroutine if we are in async mode?
162
+ # Actually, exec_driver_sql on AsyncConnection returns a CursorResult that
163
+ # has sync-like interface if used inside run_sync, but here we are inside dialect method.
164
+
165
+ # Safe way:
166
+ val = res.scalar()
167
+ if asyncio.iscoroutine(val):
168
+ version_str = await_only(val)
169
+ else:
170
+ version_str = val
171
+
172
+ except Exception:
173
+ return (0, 0)
174
+
175
+ if not version_str:
176
+ return (0, 0)
177
+
178
+ parts = str(version_str).split(".")
179
+ try:
180
+ major = int(parts[0])
181
+ minor = int(parts[1]) if len(parts) > 1 else 0
182
+ return (major, minor)
183
+ except (ValueError, IndexError):
184
+ return (0, 0)
@@ -0,0 +1,136 @@
1
+ Metadata-Version: 2.4
2
+ Name: sqlalchemy-firebird-async
3
+ Version: 0.1.0
4
+ Summary: Asyncio support for Firebird in SQLAlchemy
5
+ Project-URL: Homepage, https://github.com/attid/sqlalchemy-firebird-async
6
+ Author-email: Igor Tolstov <attid0@gmail.com>
7
+ License: MIT
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Framework :: AsyncIO
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Database
14
+ Requires-Dist: greenlet!=0.4.17
15
+ Requires-Dist: sqlalchemy-firebird>=2.0.0
16
+ Requires-Dist: sqlalchemy>=2.0.0
17
+ Provides-Extra: all
18
+ Requires-Dist: fdb>=2.0; extra == 'all'
19
+ Requires-Dist: firebirdsql>=1.0; extra == 'all'
20
+ Provides-Extra: fdb
21
+ Requires-Dist: fdb>=2.0; extra == 'fdb'
22
+ Provides-Extra: firebirdsql
23
+ Requires-Dist: firebirdsql>=1.0; extra == 'firebirdsql'
24
+ Provides-Extra: test
25
+ Requires-Dist: pytest-asyncio>=0.21; extra == 'test'
26
+ Requires-Dist: pytest>=7.0; extra == 'test'
27
+ Requires-Dist: testcontainers>=3.7.0; extra == 'test'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # sqlalchemy-firebird-async
31
+
32
+ ![Python Version](https://img.shields.io/pypi/pyversions/sqlalchemy-firebird-async)
33
+ ![License](https://img.shields.io/pypi/l/sqlalchemy-firebird-async)
34
+ ![Status](https://img.shields.io/pypi/status/sqlalchemy-firebird-async)
35
+
36
+ **Asynchronous Firebird dialect for SQLAlchemy.**
37
+
38
+ This library provides proper `asyncio` support for Firebird databases in SQLAlchemy 2.0+, allowing you to write fully asynchronous code using modern Python patterns.
39
+
40
+ It supports two underlying drivers:
41
+ 1. **`fdb`** (Recommended) - Runs the official C-based driver in a thread pool. Fast and stable.
42
+ 2. **`firebirdsql`** - Pure Python asyncio driver. Currently experimental due to upstream issues.
43
+
44
+ ## 📦 Installation
45
+
46
+ Install using pip:
47
+
48
+ ```bash
49
+ # Recommended: Install with the FDB driver (Threaded, Fast)
50
+ pip install "sqlalchemy-firebird-async[fdb]"
51
+
52
+ # Install with pure python driver (Experimental)
53
+ pip install "sqlalchemy-firebird-async[firebirdsql]"
54
+ # Note: For correct async behavior with firebirdsql, you might need a patched version:
55
+ # pip install git+https://github.com/attid/pyfirebirdsql.git
56
+ ```
57
+
58
+ ## 🚀 Quick Start
59
+
60
+ ### 1. Using FDB Driver (Recommended)
61
+
62
+ This dialect runs the official `fdb` driver in a thread pool (`run_in_executor`). While not "truly" async at the socket level, it provides the best performance and stability currently available for Firebird in Python.
63
+
64
+ **URL Scheme:** `firebird+fdb_async://`
65
+
66
+ ```python
67
+ import asyncio
68
+ from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
69
+ from sqlalchemy import text
70
+
71
+ async def main():
72
+ # Format: firebird+fdb_async://user:password@host:port/path/to/db
73
+ # Note: For Linux, ensure the path is absolute (e.g. //firebird/data/...)
74
+ dsn = "firebird+fdb_async://sysdba:masterkey@localhost:3050//firebird/data/employee.fdb"
75
+
76
+ engine = create_async_engine(dsn, echo=True)
77
+
78
+ async with engine.begin() as conn:
79
+ result = await conn.execute(text("SELECT rdb$get_context('SYSTEM', 'ENGINE_VERSION') FROM rdb$database"))
80
+ version = result.scalar()
81
+ print(f"Firebird Version: {version}")
82
+
83
+ # Using AsyncSession
84
+ async_session = async_sessionmaker(engine, expire_on_commit=False)
85
+ async with async_session() as session:
86
+ result = await session.execute(text("SELECT count(*) FROM rdb$relations"))
87
+ print(f"Total tables: {result.scalar()}")
88
+
89
+ await engine.dispose()
90
+
91
+ if __name__ == "__main__":
92
+ asyncio.run(main())
93
+ ```
94
+
95
+ ### 2. Using Native Async Driver (firebirdsql)
96
+
97
+ **Warning:** The upstream `firebirdsql` driver currently has issues with `asyncio` compatibility (bugs causing crashes or incorrect behavior).
98
+ A patched fork is available at [attid/pyfirebirdsql](https://github.com/attid/pyfirebirdsql.git), which fixes the async logic but currently exhibits significantly lower performance (approx. 4x slower than fdb).
99
+
100
+ **URL Scheme:** `firebird+firebirdsql_async://`
101
+
102
+ ```python
103
+ engine = create_async_engine(
104
+ "firebird+firebirdsql_async://sysdba:masterkey@localhost:3050//firebird/data/employee.fdb"
105
+ )
106
+ ```
107
+
108
+ ## 📊 Performance Comparison
109
+
110
+ We compared both drivers executing 5000 queries in 8 concurrent tasks (4 raw SQL + 4 ORM).
111
+
112
+ | Metric | **fdb (Threaded)** 🏆 | **firebirdsql (Patched)** | Difference |
113
+ | :--- | :--- | :--- | :--- |
114
+ | **Total Time** | **4.53s** | 116.20s | ~25x slower |
115
+ | **Avg Query Time (ORM)** | **2.54s** | 114.43s | ~45x slower |
116
+ | **Avg Query Time (Raw)** | **4.44s** | 116.14s | ~26x slower |
117
+ | **Parallel Ratio** | 6.16x | 7.94x | - |
118
+
119
+ *Benchmark details: 8 concurrent workers, 5000 rows each, total 40k rows.*
120
+
121
+ As seen above, `fdb` in a thread pool is significantly faster for high-load scenarios.
122
+
123
+ ## 🔌 Connection String Guide
124
+
125
+ | Driver | Protocol | URL Scheme |
126
+ | :--- | :--- | :--- |
127
+ | **fdb** (Recommended) | TCP/IP | `firebird+fdb_async://user:pass@host:port/db_path` |
128
+ | **firebirdsql** | TCP/IP | `firebird+firebirdsql_async://user:pass@host:port/db_path` |
129
+
130
+ ## 🤝 Contributing
131
+
132
+ Contributions are welcome! Please feel free to submit a Pull Request.
133
+
134
+ ## 📄 License
135
+
136
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,8 @@
1
+ sqlalchemy_firebird_async/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ sqlalchemy_firebird_async/fdb.py,sha256=YXBaYKX2lC3IFmfWAztwJbgZ4JsgCtFkr3rdS1jOih4,3750
3
+ sqlalchemy_firebird_async/firebirdsql.py,sha256=oS_XE5FaebHj8A40YbiUDT5jtZWbKolO-Cjlc2pmLA0,6000
4
+ sqlalchemy_firebird_async-0.1.0.dist-info/METADATA,sha256=2XjsYvOsinFxbvPPx2jSVhkiuQYCQhE9ptGxnA9yyJw,5208
5
+ sqlalchemy_firebird_async-0.1.0.dist-info/WHEEL,sha256=aha0VrrYvgDJ3Xxl3db_g_MDIW-ZexDdrc_m-Hk8YY4,105
6
+ sqlalchemy_firebird_async-0.1.0.dist-info/entry_points.txt,sha256=d6F6P0ai6bqVvRPqUJ5W0jLwHDNqLig_fDAadw4kpME,180
7
+ sqlalchemy_firebird_async-0.1.0.dist-info/licenses/LICENSE,sha256=ESYyLizI0WWtxMeS7rGVcX3ivMezm-HOd5WdeOh-9oU,1056
8
+ sqlalchemy_firebird_async-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.28.0
3
+ Root-Is-Purelib: true
4
+ Tag: py2-none-any
5
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [sqlalchemy.dialects]
2
+ firebird.fdb_async = sqlalchemy_firebird_async.fdb:AsyncFDBDialect
3
+ firebird.firebirdsql_async = sqlalchemy_firebird_async.firebirdsql:AsyncFirebirdSQLDialect
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.