From 44e45794327d9a54d227c3242231025db37518bb Mon Sep 17 00:00:00 2001 From: Artyom Abakumov Date: Mon, 20 Apr 2026 16:00:59 +0300 Subject: [PATCH 01/48] Add plugin parsing to tracemgr output --- src/firebird/driver/core.py | 2 ++ src/firebird/driver/types.py | 2 ++ 2 files changed, 4 insertions(+) diff --git a/src/firebird/driver/core.py b/src/firebird/driver/core.py index 211188c..ebc6bc9 100644 --- a/src/firebird/driver/core.py +++ b/src/firebird/driver/core.py @@ -5581,6 +5581,8 @@ def store(): '%Y-%m-%d %H:%M:%S') elif line.lstrip().startswith('flags:'): current['flags'] = line.split(':')[1].strip().split(',') + elif line.lstrip().startswith('plugins:'): + current['plugins'] = line.split(':')[1].strip().split(',') else: # pragma: no cover raise InterfaceError(f"Unexpected line in trace session list: {line}") store() diff --git a/src/firebird/driver/types.py b/src/firebird/driver/types.py index 7077aed..7ad83b7 100644 --- a/src/firebird/driver/types.py +++ b/src/firebird/driver/types.py @@ -1372,12 +1372,14 @@ class TraceSession: timestamp (datetime.datetime): Session start timestamp name (str): Session name (if defined) flags (list): List with session flag names + plugins (list): List with trace plugins for this session """ id: int user: str timestamp: datetime.datetime name: str = '' flags: list = field(default_factory=list) + plugins: list = field(default_factory=list) @dataclass class ImpData: From c6b03484e5b365bc05a9924a98297b6d8ccf9644 Mon Sep 17 00:00:00 2001 From: Artyom Abakumov Date: Wed, 22 Apr 2026 17:30:01 +0300 Subject: [PATCH 02/48] Add ability to specify plugins names for user trace session --- src/firebird/driver/core.py | 8 +++++++- src/firebird/driver/types.py | 1 + 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/firebird/driver/core.py b/src/firebird/driver/core.py index ebc6bc9..ab143f7 100644 --- a/src/firebird/driver/core.py +++ b/src/firebird/driver/core.py @@ -5496,12 +5496,13 @@ def __action(self, action: ServerAction, label: str, session_id: int) -> str: # response should contain the error message raise DatabaseError(response) return response - def start(self, *, config: str, name: str | None=None) -> int: + def start(self, *, config: str, name: str | None=None, plugins: str | list[str] | None) -> int: """Start new trace session. **(ASYNC service)** Arguments: config: Trace session configuration. name: Trace session name. + plugins: Plugins to use for the session (only for FIREBIRD 6+) Returns: Trace session ID. @@ -5511,6 +5512,11 @@ def start(self, *, config: str, name: str | None=None) -> int: spb.insert_tag(ServerAction.TRACE_START) if name is not None: spb.insert_string(SrvTraceOption.NAME, name) + if plugins is not None: + if isinstance(plugins, list): + plugins = ",".join(plugins) + spb.insert_string(SrvTraceOption.PLUGINS, plugins) + spb.insert_string(SrvTraceOption.CONFIG, config, encoding=self._srv().encoding) self._srv()._svc.start(spb.get_buffer()) response = self._srv()._fetch_line() diff --git a/src/firebird/driver/types.py b/src/firebird/driver/types.py index 7ad83b7..c95abfa 100644 --- a/src/firebird/driver/types.py +++ b/src/firebird/driver/types.py @@ -830,6 +830,7 @@ class SrvTraceOption(IntEnum): ID = 1 NAME = 2 CONFIG = 3 + PLUGINS = 4 class SrvPropertiesOption(IntEnum): """Parameters for ServerAction.PROPERTIES. From 4ae7d0c97fa234037ddaadbf7fdfae5201fda3db Mon Sep 17 00:00:00 2001 From: Artyom Abakumov Date: Wed, 22 Apr 2026 17:58:44 +0300 Subject: [PATCH 03/48] Add missing default value for plugins --- src/test.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 src/test.py diff --git a/src/test.py b/src/test.py new file mode 100644 index 0000000..467953a --- /dev/null +++ b/src/test.py @@ -0,0 +1,24 @@ +import sys +import os + +from firebird.driver.fbapi import load_api +sys.path.append(os.getcwd()) +script_dir = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(script_dir) +from firebird.driver.core import connect_server + +load_api("/home/artmkn/wspace/reps/rdb5trace/gen/Debug/firebird/lib/libfbclient.so") + +with connect_server('', user='SYSDBA', password='masterkey') as srv: + + trace_session_id = srv.trace.start(config="#MESSAGETRACE\ndatabase\n{\nenabled = true\n}", name="messagetrace") + print(trace_session_id) + + a = input() + # K = 1 + # V = TraceSession(id=1, user='SYSDBA', timestamp=..., name=, flags=['active', ' trace']) + # for k,v in srv.trace.sessions.items(): + # if v.flags[0] == 'active': + # print(f"Trace {v.name}: Plugins: {v.plugins}") + + From 96ec7c13fed9b46c7963a442af305026ad3203b9 Mon Sep 17 00:00:00 2001 From: "F.D.Castel" Date: Thu, 21 May 2026 11:48:51 -0300 Subject: [PATCH 04/48] Fix segfault in garbage collection of abandoned connection. Fix #69. The v5 iAttachment.detach() override dropped the `if self._refcnt:` guard that iAttachment_v4.detach() has. During cyclic garbage collection the iAttachment's own iReferenceCounted.__del__ can run release() first (freeing the native interface and setting _refcnt to 0); Connection.__del__ then calls detach() on the already-released interface, dereferencing freed memory and crashing with an access violation. Restore the guard so detach() is a no-op once the interface has been released. Adds a regression test that abandons connections without close() and forces cyclic GC, asserting no access violation escapes the finalizer. --- src/firebird/driver/interfaces.py | 12 ++++++-- tests/test_issues.py | 49 +++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 3 deletions(-) diff --git a/src/firebird/driver/interfaces.py b/src/firebird/driver/interfaces.py index d5d4b2c..1359d05 100644 --- a/src/firebird/driver/interfaces.py +++ b/src/firebird/driver/interfaces.py @@ -1261,9 +1261,15 @@ class iAttachment(iAttachment_v4): VERSION = 5 def detach(self) -> None: "Replaces `isc_detach_database()`. On success releases interface." - self.vtable.detach(self, self.status) - self._check() - self._refcnt -= 1 + # Guard against detaching an already-released interface. During cyclic + # garbage collection the iAttachment's own iReferenceCounted.__del__ + # may run release() before Connection.__del__ calls detach(); without + # this guard the native call dereferences freed memory and segfaults + # (issue #69). iAttachment_v4.detach already guards the same way. + if self._refcnt: + self.vtable.detach(self, self.status) + self._check() + self._refcnt -= 1 def drop_database(self) -> None: "Replaces `isc_drop_database()`. On success releases interface." self.vtable.dropDatabase(self, self.status) diff --git a/tests/test_issues.py b/tests/test_issues.py index cdfc3f2..8237d0d 100644 --- a/tests/test_issues.py +++ b/tests/test_issues.py @@ -65,3 +65,52 @@ def test_issue_65_free_then_conn_close(dsn): row = cur.execute(stmt, (2,)).fetchone() assert row is not None stmt.free() + +def test_issue_69_gc_of_abandoned_connection(dsn): + """A connection abandoned without close() and reclaimed by cyclic garbage + collection must not crash in Connection.__del__ -> iAttachment.detach(). + + During cyclic GC the iAttachment's own iReferenceCounted.__del__ may run + release() (dropping its refcount to 0 and freeing the native interface) + before Connection.__del__ calls detach(); detaching the already-released + interface dereferences freed memory and segfaults. + + On Python builds where the access violation hard-crashes the process the + worker dies (test fails). On builds where ctypes turns it into an + "Exception ignored ... in __del__" the failure is delivered via + sys.unraisablehook, which this test captures. + """ + import gc + import sys + import warnings + from firebird.driver import connect + + def abandon(): + con = connect(dsn) + cur = con.cursor() + cur.execute('select count(*) from country') + cur.fetchall() + # deliberately NO con.close(); the reference is dropped on return + + unraisable = [] + old_hook = sys.unraisablehook + sys.unraisablehook = unraisable.append + try: + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + for _ in range(5): + abandon() + gc.collect() + finally: + sys.unraisablehook = old_hook + + # The #69 crash is a native access violation (surfaced as OSError) escaping + # the finalizer; on hard-crashing builds the worker dies before reaching + # here. Other finalizer noise (e.g. a benign "invalid transaction handle" + # DatabaseError seen on some versions) is unrelated to this issue. + access_violations = [a for a in unraisable + if isinstance(a.exc_value, OSError)] + assert not access_violations, \ + f"finalizer access violation: {[a.exc_value for a in access_violations]}" + # The finalizer must still run and warn about the undisposed connection. + assert any(issubclass(w.category, ResourceWarning) for w in caught) From d032edded5568b1e0ab97c8c3cc712e75207b0dd Mon Sep 17 00:00:00 2001 From: "F.D.Castel" Date: Thu, 21 May 2026 14:18:03 -0300 Subject: [PATCH 05/48] Make ServerTraceServices.start() plugins argument optional #68 added a `plugins` keyword-only parameter to ServerTraceServices.start() but without a default value, making it required. This breaks every existing caller -- including this project's own tests/test_server.py::test_trace -- with: TypeError: ServerTraceServices.start() missing 1 required keyword-only argument: 'plugins' The method body already treats the argument as optional (`if plugins is not None:`) and its docstring documents it as FB6+ only, so restore the `= None` default. Adds a regression test asserting the parameter keeps a default of None. --- src/firebird/driver/core.py | 2 +- tests/test_server.py | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/firebird/driver/core.py b/src/firebird/driver/core.py index ab143f7..457c24b 100644 --- a/src/firebird/driver/core.py +++ b/src/firebird/driver/core.py @@ -5496,7 +5496,7 @@ def __action(self, action: ServerAction, label: str, session_id: int) -> str: # response should contain the error message raise DatabaseError(response) return response - def start(self, *, config: str, name: str | None=None, plugins: str | list[str] | None) -> int: + def start(self, *, config: str, name: str | None=None, plugins: str | list[str] | None=None) -> int: """Start new trace session. **(ASYNC service)** Arguments: diff --git a/tests/test_server.py b/tests/test_server.py index 93e1e7f..7a28f0b 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -22,6 +22,7 @@ # # See LICENSE.TXT for details. +import inspect from io import BytesIO import pytest from packaging.specifiers import SpecifierSet @@ -158,6 +159,19 @@ def test_get_limbo_transaction_ids(server_connection, db_file): ids = server_connection.database.get_limbo_transaction_ids(database=str(db_file)) assert isinstance(ids, type(list())) +def test_trace_start_plugins_is_optional(): + """Regression: ServerTraceServices.start() must keep `plugins` optional. + + #68 added `plugins` as a keyword-only parameter but without a default, + making it required and breaking every existing caller (including + `test_trace` below, and any FB3/4/5 user) with + "missing 1 required keyword-only argument: 'plugins'". The method body + already treats it as optional (`if plugins is not None:`) and the + docstring marks it FB6+ only, so it must default to None. + """ + sig = inspect.signature(driver.core.ServerTraceServices.start) + assert sig.parameters['plugins'].default is None + def test_trace(server_connection, db_file, fb_vars): trace_config = """database = %s { From f17588a01607a7593f90ad9ff09cb9ffa41029ee Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Wed, 7 Oct 2026 18:12:45 +0200 Subject: [PATCH 06/48] adjustments --- .github/FUNDING.yml | 4 ++-- .gitignore | 1 + pyproject.toml | 9 --------- 3 files changed, 3 insertions(+), 11 deletions(-) diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index 268ea1c..4b85cfe 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1,6 +1,6 @@ # These are supported funding model platforms -github: [pcisar] +github: # [pcisar] patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username @@ -12,4 +12,4 @@ lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cl polar: # Replace with a single Polar username buy_me_a_coffee: # Replace with a single Buy Me a Coffee username thanks_dev: # Replace with a single thanks.dev username -custom: # https://firebirdsql.org/en/donate/ +custom: https://firebirdsql.org/en/donate/ diff --git a/.gitignore b/.gitignore index b32f3c0..196e0e2 100644 --- a/.gitignore +++ b/.gitignore @@ -143,3 +143,4 @@ store/ # Sphinx build docs/_build docs/firebird-driver.docset + diff --git a/pyproject.toml b/pyproject.toml index b4d010a..59b0d6e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -55,15 +55,6 @@ allow-direct-references = true dependencies = [ ] -[tool.hatch.envs.gdocs] -dependencies = [ - "great-docs", -] - -[tool.hatch.envs.gdocs.scripts] -build = "great-docs build" -preview = "great-docs preview" - [tool.hatch.envs.hatch-test] extra-args = ["--host=localhost"] extra-dependencies = [ From bff25a1cb8c84986377e63699561801f1b09125a Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Thu, 8 Oct 2026 16:25:21 +0200 Subject: [PATCH 07/48] Fix redering in zensical --- CHANGELOG.md | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 57c5dea..ca38178 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,18 +8,18 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed -- #65: Segmentation fault when close connection or cursor -- #63: Exception ignored in: function Connection.__del__ -- #58: readline_timed() method appending \n to data received -- #56: Variable 'dsn' needs to be initialized in create_database() -- #53: Loss of scale when reading numeric with zero value -- #51: Exception ignored in: function Connection.__del__ ... connection shutdown +- ​#65: Segmentation fault when close connection or cursor +- ​#63: Exception ignored in: function Connection.__del__ +- ​#58: readline_timed() method appending \n to data received +- ​#56: Variable 'dsn' needs to be initialized in create_database() +- ​#53: Loss of scale when reading numeric with zero value +- ​#51: Exception ignored in: function Connection.__del__ ... connection shutdown ## [2.0.2] - 2025-05-21 ### Fixed -- #49: database host configuration not work with version 2 +- ​#49: database host configuration not work with version 2 ## [2.0.1] - 2025-05-05 @@ -31,8 +31,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed -- #22: Allow use of Firebird embedded engine for tests -- #41: Some `firebird.conf` parameters are missing in `fbapi.config_items` +- ​#22: Allow use of Firebird embedded engine for tests +- ​#41: Some `firebird.conf` parameters are missing in `fbapi.config_items` - Fix: Added validation-related info codes that were ommited in `DatabaseInfoProvider3`. - Fix: Properly handle situation when parameter `database` for `connect` and `create_database` is a DSN. @@ -71,7 +71,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed -- Fix #44 - Invalid affected_row count on multiple statements +- Fix ​#44 - Invalid affected_row count on multiple statements ## [1.10.8] - 2024-12-23 @@ -135,7 +135,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed -- #30 - It is not possible to start a transaction without specifying an isolation level +- ​#30 - It is not possible to start a transaction without specifying an isolation level The fix allows use of empty tpb in `TransactionManager.begin()` ## [1.10.2] - 2024-05-03 @@ -143,15 +143,15 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed - Mangled output for `DbInfoCode` itsens `CRYPT_PLUGIN`, `WIRE_CRYPT`, `DB_GUID` and `DB_FILE_ID` -- #34 - Pre-1970 dates causes OverflowError -- #38 - 'datetime.date' object has no attribute 'date' +- ​#34 - Pre-1970 dates causes OverflowError +- ​#38 - 'datetime.date' object has no attribute 'date' ## [1.10.1] - 2023-12-21 ### Fixed - Call iProvider.shutdown() on program exit. -- #33 - SIGABRT on interface detach. +- ​#33 - SIGABRT on interface detach. ## [1.10.0] - 2023-10-03 @@ -159,7 +159,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - #27 - Failed to establish a connection to the server on the specified port. - #15 - Documentation issue. -- Fixed issue on MacOS (see #7827 in Firebird) +- Fixed issue on MacOS (see ​#7827 in Firebird) ### Changed @@ -187,7 +187,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Wait for completion of `ServerDbServices` services that do not return data. Otherwise subsequent service calls may end with "Service is currently busy" error. - Documentation link for the driver, provided by @mariuz -- #20: Cursor.description returning () instead of None when the cursor has no rows, +- ​#20: Cursor.description returning () instead of None when the cursor has no rows, which is violation of PEP 249. Fix provided by @fdcastel ### Changed @@ -414,7 +414,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed -- Bug #4: exeption returns non ascii-127 symbols. +- Bug ​#4: exeption returns non ascii-127 symbols. The error message decode uses `.fbapi.err_encoding` value that is initialized to `locale.getpreferredencoding`. Also, the decode is now done with `errors="replace"`. - Unregistered bug: wrong handling of milliseconds in TIME and TEMEPSTAMP datatype. @@ -443,7 +443,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Unregistered bug: `sql_dialect` is used instead `db_sql_dialect` in `firebird.driver.core.create_database`. -- Bug #2: error when handling input parameters with value None +- Bug ​#2: error when handling input parameters with value None ## [1.1.0] - 2021-03-04 From bb5dd99a6958a9b634868f760e3437885085f3c3 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Thu, 8 Oct 2026 16:28:01 +0200 Subject: [PATCH 08/48] Test gihub linking --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ca38178..4110935 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed -- ​#65: Segmentation fault when close connection or cursor +- Segmentation fault when close connection or cursor (#65) - ​#63: Exception ignored in: function Connection.__del__ - ​#58: readline_timed() method appending \n to data received - ​#56: Variable 'dsn' needs to be initialized in create_database() From d1c616be57ff8f9b631686c1910253fff3e3d9da Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Thu, 8 Oct 2026 16:31:47 +0200 Subject: [PATCH 09/48] Another --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4110935..e23d1d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed -- Segmentation fault when close connection or cursor (#65) +- GH-65: Segmentation fault when close connection or cursor - ​#63: Exception ignored in: function Connection.__del__ - ​#58: readline_timed() method appending \n to data received - ​#56: Variable 'dsn' needs to be initialized in create_database() From 64296cce88b045baf73a78a26674f13c77b0fd54 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Thu, 8 Oct 2026 16:32:54 +0200 Subject: [PATCH 10/48] And another --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e23d1d0..dd30ca6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed -- GH-65: Segmentation fault when close connection or cursor +- GH-65 Segmentation fault when close connection or cursor - ​#63: Exception ignored in: function Connection.__del__ - ​#58: readline_timed() method appending \n to data received - ​#56: Variable 'dsn' needs to be initialized in create_database() From 9a79d6b3062c7cd935796108bfb566072b1b3271 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Thu, 8 Oct 2026 16:34:04 +0200 Subject: [PATCH 11/48] And another --- CHANGELOG.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dd30ca6..c5fb423 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,9 +9,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed - GH-65 Segmentation fault when close connection or cursor -- ​#63: Exception ignored in: function Connection.__del__ -- ​#58: readline_timed() method appending \n to data received -- ​#56: Variable 'dsn' needs to be initialized in create_database() +- #63: Exception ignored in: function Connection.__del__ +- gh-58: readline_timed() method appending \n to data received +- `#56``: Variable 'dsn' needs to be initialized in create_database() - ​#53: Loss of scale when reading numeric with zero value - ​#51: Exception ignored in: function Connection.__del__ ... connection shutdown From 0a8ec78df4f8ed6de31daf5ec6f96fc6f118d089 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Thu, 8 Oct 2026 16:37:40 +0200 Subject: [PATCH 12/48] Final adjustment --- CHANGELOG.md | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c5fb423..8c1192a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,17 +9,17 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed - GH-65 Segmentation fault when close connection or cursor -- #63: Exception ignored in: function Connection.__del__ -- gh-58: readline_timed() method appending \n to data received -- `#56``: Variable 'dsn' needs to be initialized in create_database() -- ​#53: Loss of scale when reading numeric with zero value -- ​#51: Exception ignored in: function Connection.__del__ ... connection shutdown +- GH-63: Exception ignored in: function Connection.__del__ +- GH-58: readline_timed() method appending \n to data received +- GH-56: Variable 'dsn' needs to be initialized in create_database() +- GH-53: Loss of scale when reading numeric with zero value +- GH-51: Exception ignored in: function Connection.__del__ ... connection shutdown ## [2.0.2] - 2025-05-21 ### Fixed -- ​#49: database host configuration not work with version 2 +- GH-49: database host configuration not work with version 2 ## [2.0.1] - 2025-05-05 @@ -31,8 +31,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed -- ​#22: Allow use of Firebird embedded engine for tests -- ​#41: Some `firebird.conf` parameters are missing in `fbapi.config_items` +- GH-22: Allow use of Firebird embedded engine for tests +- GH-41: Some `firebird.conf` parameters are missing in `fbapi.config_items` - Fix: Added validation-related info codes that were ommited in `DatabaseInfoProvider3`. - Fix: Properly handle situation when parameter `database` for `connect` and `create_database` is a DSN. @@ -71,7 +71,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed -- Fix ​#44 - Invalid affected_row count on multiple statements +- Fix GH-44 - Invalid affected_row count on multiple statements ## [1.10.8] - 2024-12-23 @@ -135,7 +135,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed -- ​#30 - It is not possible to start a transaction without specifying an isolation level +- GH-30 - It is not possible to start a transaction without specifying an isolation level The fix allows use of empty tpb in `TransactionManager.begin()` ## [1.10.2] - 2024-05-03 @@ -143,15 +143,15 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed - Mangled output for `DbInfoCode` itsens `CRYPT_PLUGIN`, `WIRE_CRYPT`, `DB_GUID` and `DB_FILE_ID` -- ​#34 - Pre-1970 dates causes OverflowError -- ​#38 - 'datetime.date' object has no attribute 'date' +- GH-34 - Pre-1970 dates causes OverflowError +- GH-38 - 'datetime.date' object has no attribute 'date' ## [1.10.1] - 2023-12-21 ### Fixed - Call iProvider.shutdown() on program exit. -- ​#33 - SIGABRT on interface detach. +- GH-33 - SIGABRT on interface detach. ## [1.10.0] - 2023-10-03 @@ -159,7 +159,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - #27 - Failed to establish a connection to the server on the specified port. - #15 - Documentation issue. -- Fixed issue on MacOS (see ​#7827 in Firebird) +- Fixed issue on MacOS (see GH-7827 in Firebird) ### Changed @@ -187,7 +187,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Wait for completion of `ServerDbServices` services that do not return data. Otherwise subsequent service calls may end with "Service is currently busy" error. - Documentation link for the driver, provided by @mariuz -- ​#20: Cursor.description returning () instead of None when the cursor has no rows, +- GH-20: Cursor.description returning () instead of None when the cursor has no rows, which is violation of PEP 249. Fix provided by @fdcastel ### Changed @@ -414,7 +414,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed -- Bug ​#4: exeption returns non ascii-127 symbols. +- Bug GH-4: exeption returns non ascii-127 symbols. The error message decode uses `.fbapi.err_encoding` value that is initialized to `locale.getpreferredencoding`. Also, the decode is now done with `errors="replace"`. - Unregistered bug: wrong handling of milliseconds in TIME and TEMEPSTAMP datatype. @@ -443,7 +443,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Unregistered bug: `sql_dialect` is used instead `db_sql_dialect` in `firebird.driver.core.create_database`. -- Bug ​#2: error when handling input parameters with value None +- Bug GH-2: error when handling input parameters with value None ## [1.1.0] - 2021-03-04 From 7c311cee691c8acd0b0c75388846795205c0bba0 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Thu, 8 Oct 2026 16:47:00 +0200 Subject: [PATCH 13/48] Migrate documentation from Sphinx to Zensical --- .gitignore | 10 +- .readthedocs.yml | 23 +- docs/Makefile | 20 - docs/_static/basic.css | 703 ---- docs/_static/dialog-note.png | Bin 1582 -> 0 bytes docs/_static/dialog-seealso.png | Bin 1502 -> 0 bytes docs/_static/dialog-topic.png | Bin 1910 -> 0 bytes docs/_static/dialog-warning.png | Bin 1391 -> 0 bytes docs/changelog.txt | 429 --- docs/conf.py | 211 -- docs/{_static => docs/assets}/fb-favicon.png | Bin docs/docs/changelog.md | 1 + docs/docs/getting-started.md | 334 ++ docs/docs/index.md | 49 + docs/docs/license.md | 23 + .../python-db-api-compliance.md} | 47 +- docs/{ref-config.txt => docs/ref-config.md} | 23 +- docs/docs/ref-core.md | 109 + docs/docs/ref-fbapi.md | 551 +++ docs/{ref-hooks.txt => docs/ref-hooks.md} | 17 +- docs/docs/ref-intf.md | 180 + docs/{ref-main.txt => docs/ref-main.md} | 33 +- docs/docs/ref-types.md | 291 ++ docs/docs/usage-guide.md | 3235 ++++++++++++++++ docs/getting-started.txt | 329 -- docs/index.txt | 58 - docs/license.txt | 6 - docs/make-docset | 2 - docs/make.bat | 35 - docs/ref-core.txt | 101 - docs/ref-fbapi.txt | 451 --- docs/ref-intf.txt | 152 - docs/ref-types.txt | 214 -- docs/reference.txt | 19 - docs/requirements.txt | 4 - docs/usage-guide.txt | 3278 ----------------- docs/zensical.toml | 45 + pyproject.toml | 16 +- src/firebird/driver/core.py | 29 +- src/firebird/driver/fbapi.py | 6 +- src/firebird/driver/interfaces.py | 2 +- src/firebird/driver/types.py | 2 +- 42 files changed, 4903 insertions(+), 6135 deletions(-) delete mode 100644 docs/Makefile delete mode 100644 docs/_static/basic.css delete mode 100644 docs/_static/dialog-note.png delete mode 100644 docs/_static/dialog-seealso.png delete mode 100644 docs/_static/dialog-topic.png delete mode 100644 docs/_static/dialog-warning.png delete mode 100644 docs/changelog.txt delete mode 100644 docs/conf.py rename docs/{_static => docs/assets}/fb-favicon.png (100%) create mode 120000 docs/docs/changelog.md create mode 100644 docs/docs/getting-started.md create mode 100644 docs/docs/index.md create mode 100644 docs/docs/license.md rename docs/{python-db-api-compliance.txt => docs/python-db-api-compliance.md} (81%) rename docs/{ref-config.txt => docs/ref-config.md} (61%) create mode 100644 docs/docs/ref-core.md create mode 100644 docs/docs/ref-fbapi.md rename docs/{ref-hooks.txt => docs/ref-hooks.md} (56%) create mode 100644 docs/docs/ref-intf.md rename docs/{ref-main.txt => docs/ref-main.md} (77%) create mode 100644 docs/docs/ref-types.md create mode 100644 docs/docs/usage-guide.md delete mode 100644 docs/getting-started.txt delete mode 100644 docs/index.txt delete mode 100644 docs/license.txt delete mode 100755 docs/make-docset delete mode 100644 docs/make.bat delete mode 100644 docs/ref-core.txt delete mode 100644 docs/ref-fbapi.txt delete mode 100644 docs/ref-intf.txt delete mode 100644 docs/ref-types.txt delete mode 100644 docs/reference.txt delete mode 100644 docs/requirements.txt delete mode 100644 docs/usage-guide.txt create mode 100644 docs/zensical.toml diff --git a/.gitignore b/.gitignore index 196e0e2..d142c1d 100644 --- a/.gitignore +++ b/.gitignore @@ -71,6 +71,8 @@ instance/ # Sphinx documentation docs/_build/ +zdoc/site/ +zdoc/firebird-driver.docset/ # PyBuilder target/ @@ -118,9 +120,6 @@ venv.bak/ # Rope project settings .ropeproject -# mkdocs documentation -/site - # mypy .mypy_cache/ .dmypy.json @@ -140,7 +139,6 @@ dmypy.json notes/ store/ -# Sphinx build -docs/_build +# Zensical build +docs/site docs/firebird-driver.docset - diff --git a/.readthedocs.yml b/.readthedocs.yml index 279e491..ef41ab0 100644 --- a/.readthedocs.yml +++ b/.readthedocs.yml @@ -1,20 +1,15 @@ -# .readthedocs.yml -# Read the Docs configuration file -# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details - -# Required version: 2 -# Build documentation in the docs/ directory with Sphinx -sphinx: - configuration: docs/conf.py - build: - os: "ubuntu-22.04" + os: ubuntu-24.04 tools: python: "3.11" - -# Optionally set the version of Python and requirements required to build your docs -python: + jobs: install: - - requirements: docs/requirements.txt + - pip install . zensical mkdocstrings-python + build: + html: + - cd docs && zensical build + post_build: + - mkdir -p $READTHEDOCS_OUTPUT/html/ + - cp --recursive docs/site/. $READTHEDOCS_OUTPUT/html/ diff --git a/docs/Makefile b/docs/Makefile deleted file mode 100644 index d4bb2cb..0000000 --- a/docs/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -# Minimal makefile for Sphinx documentation -# - -# You can set these variables from the command line, and also -# from the environment for the first two. -SPHINXOPTS ?= -SPHINXBUILD ?= sphinx-build -SOURCEDIR = . -BUILDDIR = _build - -# Put it first so that "make" without argument is like "make help". -help: - @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) - -.PHONY: help Makefile - -# Catch-all target: route all unknown targets to Sphinx using the new -# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). -%: Makefile - @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/docs/_static/basic.css b/docs/_static/basic.css deleted file mode 100644 index 20b93ce..0000000 --- a/docs/_static/basic.css +++ /dev/null @@ -1,703 +0,0 @@ -/* -- main layout ----------------------------------------------------------- */ - -div.clearer { - clear: both; -} - -/* -- relbar ---------------------------------------------------------------- */ - -div.related { - width: 100%; - font-size: 90%; -} - -div.related h3 { - display: none; -} - -div.related ul { - margin: 0; - padding: 0 0 0 10px; - list-style: none; -} - -div.related li { - display: inline; -} - -div.related li.right { - float: right; - margin-right: 5px; -} - -/* -- sidebar --------------------------------------------------------------- */ - -div.sphinxsidebarwrapper { - padding: 10px 5px 0 10px; -} - -div.sphinxsidebar { - float: left; - width: 230px; - margin-left: -100%; - font-size: 90%; - word-wrap: break-word; - overflow-wrap : break-word; -} - -div.sphinxsidebar ul { - list-style: none; -} - -div.sphinxsidebar ul ul, -div.sphinxsidebar ul.want-points { - margin-left: 20px; - list-style: square; -} - -div.sphinxsidebar ul ul { - margin-top: 0; - margin-bottom: 0; -} - -div.sphinxsidebar form { - margin-top: 10px; -} - -div.sphinxsidebar input { - border: 1px solid #98dbcc; - font-family: sans-serif; - font-size: 1em; -} - -div.sphinxsidebar #searchbox input[type="text"] { - float: left; - width: 80%; - padding: 0.25em; - box-sizing: border-box; -} - -div.sphinxsidebar #searchbox input[type="submit"] { - float: left; - width: 20%; - border-left: none; - padding: 0.25em; - box-sizing: border-box; -} - - -img { - border: 0; - max-width: 100%; -} - -/* -- search page ----------------------------------------------------------- */ - -ul.search { - margin: 10px 0 0 20px; - padding: 0; -} - -ul.search li { - padding: 5px 0 5px 20px; - background-image: url(file.png); - background-repeat: no-repeat; - background-position: 0 7px; -} - -ul.search li a { - font-weight: bold; -} - -ul.search li div.context { - color: #888; - margin: 2px 0 0 30px; - text-align: left; -} - -ul.keywordmatches li.goodmatch a { - font-weight: bold; -} - -/* -- index page ------------------------------------------------------------ */ - -table.contentstable { - width: 90%; - margin-left: auto; - margin-right: auto; -} - -table.contentstable p.biglink { - line-height: 150%; -} - -a.biglink { - font-size: 1.3em; -} - -span.linkdescr { - font-style: italic; - padding-top: 5px; - font-size: 90%; -} - -/* -- general index --------------------------------------------------------- */ - -table.indextable { - width: 100%; -} - -table.indextable td { - text-align: left; - vertical-align: top; -} - -table.indextable ul { - margin-top: 0; - margin-bottom: 0; - list-style-type: none; -} - -table.indextable > tbody > tr > td > ul { - padding-left: 0em; -} - -table.indextable tr.pcap { - height: 10px; -} - -table.indextable tr.cap { - margin-top: 10px; - background-color: #f2f2f2; -} - -img.toggler { - margin-right: 3px; - margin-top: 3px; - cursor: pointer; -} - -div.modindex-jumpbox { - border-top: 1px solid #ddd; - border-bottom: 1px solid #ddd; - margin: 1em 0 1em 0; - padding: 0.4em; -} - -div.genindex-jumpbox { - border-top: 1px solid #ddd; - border-bottom: 1px solid #ddd; - margin: 1em 0 1em 0; - padding: 0.4em; -} - -/* -- domain module index --------------------------------------------------- */ - -table.modindextable td { - padding: 2px; - border-collapse: collapse; -} - -/* -- general body styles --------------------------------------------------- */ - -div.body { - min-width: 450px; - max-width: 1920px; -} - -div.body p, div.body dd, div.body li, div.body blockquote { - -moz-hyphens: auto; - -ms-hyphens: auto; - -webkit-hyphens: auto; - hyphens: auto; -} - -a.headerlink { - visibility: hidden; -} - -h1:hover > a.headerlink, -h2:hover > a.headerlink, -h3:hover > a.headerlink, -h4:hover > a.headerlink, -h5:hover > a.headerlink, -h6:hover > a.headerlink, -dt:hover > a.headerlink, -caption:hover > a.headerlink, -p.caption:hover > a.headerlink, -div.code-block-caption:hover > a.headerlink { - visibility: visible; -} - -div.body p.caption { - text-align: inherit; -} - -div.body td { - text-align: left; -} - -.first { - margin-top: 0 !important; -} - -p.rubric { - margin-top: 30px; - font-weight: bold; -} - -img.align-left, .figure.align-left, object.align-left { - clear: left; - float: left; - margin-right: 1em; -} - -img.align-right, .figure.align-right, object.align-right { - clear: right; - float: right; - margin-left: 1em; -} - -img.align-center, .figure.align-center, object.align-center { - display: block; - margin-left: auto; - margin-right: auto; -} - -.align-left { - text-align: left; -} - -.align-center { - text-align: center; -} - -.align-right { - text-align: right; -} - -/* -- sidebars -------------------------------------------------------------- */ - -div.sidebar { - margin: 0 0 0.5em 1em; - border: 1px solid #ddb; - padding: 7px 7px 0 7px; - background-color: #ffe; - width: 40%; - float: right; -} - -p.sidebar-title { - font-weight: bold; -} - -/* -- topics ---------------------------------------------------------------- */ - -div.topic { - border: 1px solid #ccc; - padding: 7px 7px 0 7px; - margin: 10px 0 10px 0; -} - -p.topic-title { - font-size: 1.1em; - font-weight: bold; - margin-top: 10px; -} - -/* -- admonitions ----------------------------------------------------------- */ - -div.admonition { - margin-top: 10px; - margin-bottom: 10px; - padding: 7px; -} - -div.admonition dt { - font-weight: bold; -} - -div.admonition dl { - margin-bottom: 0; -} - -p.admonition-title { - margin: 0px 10px 5px 0px; - font-weight: bold; -} - -div.body p.centered { - text-align: center; - margin-top: 25px; -} - -/* -- code displays --------------------------------------------------------- */ - -pre { - overflow: auto; - overflow-y: hidden; /* fixes display issues on Chrome browsers */ -} - -span.pre { - -moz-hyphens: none; - -ms-hyphens: none; - -webkit-hyphens: none; - hyphens: none; -} - -td.linenos pre { - padding: 5px 0px; - border: 0; - background-color: transparent; - color: #aaa; -} - -table.highlighttable { - margin-left: 0.5em; -} - -table.highlighttable td { - padding: 0 0.5em 0 0.5em; -} - -div.code-block-caption { - padding: 2px 5px; - font-size: small; -} - -div.code-block-caption code { - background-color: transparent; -} - -div.code-block-caption + div > div.highlight > pre { - margin-top: 0; -} - -div.code-block-caption span.caption-number { - padding: 0.1em 0.3em; - font-style: italic; -} - -div.code-block-caption span.caption-text { -} - -div.literal-block-wrapper { - padding: 1em 1em 0; -} - -div.literal-block-wrapper div.highlight { - margin: 0; -} - -code.descname { - background-color: transparent; - font-weight: bold; - font-size: 1.2em; - border-style: none; - padding: 0; -} - -code.descclassname { - background-color: transparent; - border-style: none; - padding: 0; -} - -code.xref, a code { - background-color: transparent; - font-weight: bold; - border-style: none; - padding: 0; -} - -h1 code, h2 code, h3 code, h4 code, h5 code, h6 code { - background-color: transparent; -} - -.viewcode-link { - float: right; -} - -.viewcode-back { - float: right; - font-family: sans-serif; -} - -div.viewcode-block:target { - margin: -1px -10px; - padding: 0 10px; -} - -/* -- math display ---------------------------------------------------------- */ - -img.math { - vertical-align: middle; -} - -div.body div.math p { - text-align: center; -} - -span.eqno { - float: right; -} - -span.eqno a.headerlink { - position: relative; - left: 0px; - z-index: 1; -} - -div.math:hover a.headerlink { - visibility: visible; -} - -/* -- printout stylesheet --------------------------------------------------- */ - -@media print { - div.document, - div.documentwrapper, - div.bodywrapper { - margin: 0 !important; - width: 100%; - } - - div.sphinxsidebar, - div.related, - div.footer, - #top-link { - display: none; - } -} - -/* -- My additions ---------------------------------------------------------- */ - -div.note { - color: black; - border: 2px solid #7a9eec; - border-right-style: none; - border-left-style: none; - padding: 10px 20px 0px 60px; - background: #e1ecfe url(dialog-note.png) no-repeat 10px 8px; -} - -div.danger { - color: black; - border: 2px solid #fbc2c4; - border-right-style: none; - border-left-style: none; - padding: 10px 20px 0px 60px; - background: #fbe3e4 url(dialog-note.png) no-repeat 10px 8px; -} - -div.attention { - color: black; - border: 2px solid #ffd324; - border-right-style: none; - border-left-style: none; - padding: 10px 20px 0px 60px; - background: #fff6bf url(dialog-note.png) no-repeat 10px 8px; -} - -div.caution { - color: black; - border: 2px solid #ffd324; - border-right-style: none; - border-left-style: none; - padding: 10px 20px 0px 60px; - background: #fff6bf url(dialog-warning.png) no-repeat 10px 8px; -} - -div.important { - color: black; - background: #fbe3e4 url(dialog-seealso.png) no-repeat 10px 8px; - border: 2px solid #fbc2c4; - border-left-style: none; - border-right-style: none; - padding: 10px 20px 0px 60px; -} - -div.seealso { - color: black; - background: #fff6bf url(dialog-seealso.png) no-repeat 10px 8px; - border: 2px solid #ffd324; - border-left-style: none; - border-right-style: none; - padding: 10px 20px 0px 60px; -} - -div.hint, div.tip { - color: black; - background: #eeffcc url(dialog-topic.png) no-repeat 10px 8px; - border: 2px solid #aacc99; - border-left-style: none; - border-right-style: none; - padding: 10px 20px 0px 60px; -} - -div.admonition-example { - color: black; - background: white url(dialog-topic.png) no-repeat 10px 8px; - border: 2px solid #aacc99; - border-left-style: none; - border-right-style: none; - padding: 10px 0px 20px 60px; -} -div.warning, div.error { - color: black; - background: #fbe3e4 url(dialog-warning.png) no-repeat 10px 8px; - border: 2px solid #fbc2c4; - border-right-style: none; - border-left-style: none; - padding: 10px 20px 0px 60px; -} - -p { - text-align: justify; - padding-bottom: 5px; -} - -h1 { - background: #fff6bf; - border: 2px solid #ffd324; - border-left-style: none; - border-right-style: none; - padding: 10px 10px 10px 10px; - text-align: center; -} - -h2 { - /* background: #eeffcc; */ - border: 2px solid #aacc99; - border-left-style: none; - border-right-style: none; - border-top-style: none; - padding: 10px 0px 0px 0px; - /* text-align: center; */ -} - -h3 { - /* background: #eeffcc; */ - border: 1px solid #7a9eec; - border-left-style: none; - border-right-style: none; - border-top-style: none; - padding: 0; - /* text-align: center; */ -} - -h4 { - background: #eeffcc; - /* border: 1px solid #aacc99; */ - border-left-style: none; - border-right-style: none; - border-top-style: none; - padding: 5px 5px 5px 5px; - /* text-align: center; */ -} - -cite { - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - border-radius: 3px; - border: 1px solid #e1e1e8; - background: #f7f7f9; - margin: 0 0 10px; - padding: 0 5px 0 5px; - font-size: 13px; - font-style: italic; -} - -.program { - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - border-radius: 3px; - border: 1px solid #e1e1e8; - background: #f7f7f9; - margin: 0 0 10px; - padding: 0 5px 0 5px; - font-size: 13px; -} - -/* dt/dd on single line */ - -dl.field-list { - display: grid; - grid-template-columns: max-content auto; -} - -dt.field-list { - grid-column-start: 1; -} - -dt.field-odd:after { - content: ':'; -} - -dt.field-even:after { - content: ':'; -} - -dd.field-list { - grid-column-start: 2; -} - -hr.docutils { - font-weight: bold; -/* border: 2px solid #7a9eec; */ - border: 2px solid grey; - border-left-style: none; - border-right-style: none; - border-top-style: none; -} - -div.versionadded { - color: black; -/* padding: 10px 0 0 10px; */ - font-weight: bold; - margin: 5px 0; -} - -div.versionchanged { - color: black; -/* padding: 0 10px 0 0; */ - font-weight: bold; - margin: 5px 0; -} - -span.added { - background: #eeffcc ; - border: 2px solid #aacc99; - border-left-style: none; - border-right-style: none; - padding: 5px; -} - -span.changed { - background: #fbe3e4 ; - border: 2px solid #fbc2c4; - border-left-style: none; - border-right-style: none; - padding: 5px; -} - -dl.class, dl.exception, dl.data, dl.function { -/* background: #fbe3e4 ;*/ - border: 1px solid grey; - border-top-style: none; - border-left-style: none; - border-right-style: none; -/* padding: 3px;*/ -} - -dt.py { - background: #f8f8f8; -/* border: 2px solid #aacc99;*/ -/* border: 2px solid #ffcccc; /*#ffd324;*/ -/* border: 2px solid #fbc2c4;*/ - border: 1px solid #e1e1e8; - border-top-style: none; - border-left-style: none; -/* border-right-style: none; */ - padding: 2px 5px; -} diff --git a/docs/_static/dialog-note.png b/docs/_static/dialog-note.png deleted file mode 100644 index 263fbd5866aef1ce3645d768fbf55def9a091905..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1582 zcmV+}2GRM6P)k@WH7pQF=3=faW zkFSqR=8AIgXBSA;Hc`EO&K^N)42Y`_9UkcY+JOPZzW)_SXY=A^lj%j;c6NwBgJ_tV zm_2r=oma1nQ4OegJG6y4*V7pt+<)-viajx2cgoi@dv1pQz5%6oPs>nSm~*w?TqQVv zob8dII{c&Oe%S1c$Jb4}_O0hohn`**8Ge(}Coiu}Aq2|y9sKoAe_L3{Is>OKFbSRv z1pSn5A0ELYKmLQ6BwuOzH&f_kC zpw7uXeVu-psxJ`U5$EUY>gJ?Py7zS&L7kH>03>~lEiK4GzOF#Bu=x@I$Wn<&a}!AV z0JO@7l0!?lsTn6_uHD-u=x*nv?jh4tOM8aU5Jm$S4XgGI1^n1jw1Qj)a0G^`sW^46 z`zk{v@<5WOf#ro&h@# znjak7C0?~s9=SM_n9NYjv(wK7=2M5YtS{PKY$ zvq{93_SMB}%_$-0$B^l1M4*|BZ#$YIXIuaXZY|uu(-Vrempj=|${=$lGCK?Q%G0#? z`m+#hhFpCs04oQ|EN0RVf?FVz z;UBke#-&y%!v?064Rok zOzr0t(XWi*Ji3QBXXf%JRoe>fIM6Q~a~|x{=CxG~y=Q>o+w;yR!_$*li|?MfjH_0w z4(~z?Yj=n@ipBh~`I%&-^WdPS`V7dV>N~21K#jH|clB`PgWJ~4*uv-kzRU4neaIZ( zs_AL~J|J*?3i;mzZ}f)kj*(jv-9BB_qC@+I5-iVl$9ByRp&N*X5L#OY%C2rk diff --git a/docs/_static/dialog-seealso.png b/docs/_static/dialog-seealso.png deleted file mode 100644 index 3eb7b05c84809454c095bcb61b27d83585540bb2..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1502 zcmV<41tI#0P)HR%3`p(HB`no_vu~6N}ZlRFC*?c+Y%$zyD-}&au z&JZ)>K^AeZ6L@^ummZ&X*Yn)70D$d6!LJ^l=6+BDv~c!{RYJijk54Ok5CT{{e~oil z-TFEbX!ZECIrm*akb>H(dS&g?FP4)K%^sh&_`V4c2m&fb&2G#rtri=XzfzzG^{B_E zHQpZqA_x*72n38CJd|Gu&#E_aHK*$b&n|7-ZLgos|A5D*S!OO3tj^fh z_!0W`3$WRQ%?5InVvwcc=cez&6S48H4!ouBxMu;6Pg_j_`(_qbYqix+<`vH*0k)O-56 zud&1uzgHhmFx075FBE*UbpHBBSI%oxLe?+@Zf!Q;*6vT#lyW3w4JY9MkgFEMG%bvd zj938nr^2Tc@c6W~RmHXIm(1Ou1kFAG0Fw%UlRqSTi54)VcO>U1an?Yy3vuG~@rZ85 z-uG|Ozewj~6o}vV-Rqv(Ci;8JElAxFv;gud8$jGKcnWCQ?Erp*KC zIXKaBJYt&WcE4BOor#q#1Dk6q78K>?<|1J9K#&Rskgt}(!EXFJ*vh>lSE3{1Loyf| z&3UuoJ;5w7Y;*zuDqMB2!UCtx{28%r>ovbu_h-v=W&y&2n({i=gf#-m76=0Q&NB3m zb>eW#zGx^K*vpKg0NMp9e=$o8=`Dj;l=Lz_SWyF}Y_f*liLBCL1t~h-HRlkcb2k zDMX|u0swmZd)fkBa>Y+ujj{N7B|et!O2BRM{{EheXKZP~kP#GW?m+0WbOJ~ZO^HPi?D-I-Z@Rh)4kw5h(x^0Lp=##*zNcjveFS!C+x=g(!SP+wgD|a?&Pu zP7Fa!$fU164o-xU8bl<3l(%90fD)HVwznQAX`EZL=V6*OcF^rX8}#?vph{K*-aJ52Fh0c1LTj{W~QdMmlr4dytt0lBR3q?&; zsf}7ieW{ceqQ0~w%0ngR(l(+>6RT|+k)U#E5K0IT8=Mf^q}b(RJRV=>K69@7oZW{E z6%PeG5mk@0w56kc*8i=4U(N#l&kxlzdElw1LXir#G9KKfp!(p+CIA4}as(RoJ?ph< z1O7I&f4_Oh0lvTIXM4f;uUc2F*Hc}+k+#-Wgu^;CM({lsi;Ii6bn(1#X=2n?p8Ult zFa3J(jsOe{JflYw)=*=zShA`mbU-k=^sX0S3bG^fyY9h&Y0*p?-h1EjYvd&-0xsN}5e{ec8zp`u9n(Vo=?+@1vuxr;( zdmq{sySgZ`X-yEFtvWOgk1=u?K@veSA{RswfCnfq-Vjh%=E~LCoS`1w+!r}> z`egsc4Sj>7qo=I@ro(Oqz;w2~xpQOK_66FLgqDN`0whSeMC33|HYc(f!R7=@<79G1 zR#?~UctgM_n@*u@OS`XsbC~ID`%QIj>OTwYZ0%eZ%2h0^Y}4Vx_lPN%Kn_7UM6fv{ zi!o+0P8Ja?jWdIDG6RBDf;y{S&XkIM_uZ#~={xJ+gud6+5RKznriy?F03ZoPF5|En zk;92O#FS(p7l7|GQp#7bUC(1g#h|W*3RRm{G^d)Oyw!CBDCI>pp}|u&OviJALUW1W z5XfPSY{p=J20;=aPXl~c`BbR53&8+ajL0`#54zx_d_P(@05PouWhWVvm|mz_@rdpL z%pro!h%5%OI3t@Fa~VM@U-?0l0G~0c*1ZRa_*l7=MN?FF77CV; zEm~y&Hi2x;$YdNQ=VWLM6-Ror^Ck1VCFRVT6^W*xu2q7Jnai8PTCP~O7}F-}2Jk%d zx7RL?mRB}6dR!yt@?tf=@vcNFq!Z7Tt#q;MPAyjKiMhNvTru2n!C5w9&wr&dH~DBl zXojvc;|pzxI6l^@7iZ|Y^bJcm^55Je(FYX)}8FA}7hJYg1-a35r zueOloU{^~#GCY|bHykfJezouxm?|xcg}XZ2k`E^1(H;)UgKOs^&36r^nqq64qWZ=c zo_~(p(%U&WIB0zCpV5vzKj{tWp?`dH$8JN3$mEKqfFjN_hUtt&LRvl?;3b_4Ly)_H zc+f9d648MEqka3H6{TYF$yZ+d&7W_TpWP1N)t8?C*mbS%o_zO+NH&HNnVfaiHVO$w zN(#;#oeP7QYhS!Lk#s%h(}sZPo){lDi-q#w?ZlS^0089E>ACc^SXl6oRGyWdnJs7M z(n(@WGF`dv9Xr~do}Hc4HBsTj+OAxgCIxwRDY=&f@bb(1b5i;r&s>|KWevgAhEs`s z^x?6uUHa#H+b(``bm!Rk$tPB?jOqkRaAG~DPJIy589rD_Zf&U@k?op$|ML2Q6W`mj zV^yjpsV__mICk-FrhqlwD-exEzvwzub@1)O*BsXwdU5c%**o47Zr}0v!C0c_v4^*8 zK~K+GG)5!fTmvH@n_Iv;Zy(0^_{8P;jK1#Bp%?5s>Hq+=Hs>GOve|~O7~Xi}PslEm z;7Sh-4FL$vK|VL-<*a9NcX#vCnx=$dOrcyhK}f5*DU#?W3N0#5)c%sGQnK9pimif5HF z4xc%b`Q`k4vHV$+3KxK^jqc}hKnD=0MR0n$WKK?IhdVoaWpi_P-|pQ%*EVf>1k=-H zJDsi^IC5m<)oRriweP65#MgsrP)i1&8>;`03jjjtbb7j@qvM{jv9Z?C(NRC2&yO8H ze*BM~=Xn79n$UFzRPCK#bEB>$pqi*&8$}I72M}m)Z*TT}pJy_eVoksWVAn#{!U162 wYzgYQ39nnK)ttN0UffXS^-8b1am$VPZ%s-(_>=>Px# diff --git a/docs/_static/dialog-warning.png b/docs/_static/dialog-warning.png deleted file mode 100644 index 7233d45d8e6e41ef8fcb318c76303a9b6f23997e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1391 zcmV-#1(5oQP)}piCG~<@Tj_&{ee%V|SZW{gB8?y>5~HGEkRU`Q5xgR16NK8$#%7av&gnyv zB_>9ji%*39&LbK3qFu zI7(%ZZ%;}2Gqh=wf?-g1;X+qD8r}8{{PEcV%0X!tqH%6yq(DC>&`hf#DjvXW3(1702fiEY= zF5vsm0&oGwD!P6+uzb1JdigTStXXLJ`Pjl?)VXtsUA;>7;>9+ps^67D`lthR!lCrM zJiGbuAzhIO`u_b0*{$vea+<+#n+u)TG0)=^W&Y8i0fonJZU{&O3K7Vlni6`w*i02KV;P{rfRu zG0etBGUm-QC7c=+fU_{mF@F3e|CA|e+x6?%3JOrCPscC}T3cI*Mx&UfiIS0lW6Kua z*4E+=1XR`QT~P`vMhu|BsqFlGD_&EBWm!0O?*~ty__PKSBsxE>~io%jH4{flNukRa8X# z{rjXQCrg{pH?0i59u|NFLJ0B8)HQ2(TUCW{yU};B)sYgKfwF=i#fQ*|T%prYYO&>#^_Jg-l9HIC3}~D2jrjDCoMLxDnFn#I<)X9Z#O% zl~TASP4c~kT|)vm3aV6;lT*TB*>>d$((gwvEKE2_WWLjh)9HL~UI>A6!v?geQ)#cO zBP%CIQ>6UickujYfDG8-Td-iF{q<|n@$@N&XN+4a)1MXii!#xt%)zy89UYGz zG12e0NnI~2gPDT@C~$aEUY=^+y^GP-hO?w((CCB^XqtxXDMlUN#ETcC z1p+4hp6CQXDP-AvzM{13Y_09qE$nO8qUGca8odyL^73*nUc5M{b0Gw_%uGDnx6}FT z856u-Rdc(;WsuwJSM3x1@yun*tghR)G2?Oc_3NRv6|2V>LcBLlv~F)$efs`;+#5F% zJ#z;0`E&f~>DJ4JhLgbjz5vpKd|!698oPE4fasPj{qtqSV!U}nQhK`b970DyKML_) z0Ovbsj@-OC=8MgnrPMUAEG)wS)5J22?y+HDnPzw2Z#-bF|D0)J#^W@3.0.10, 4.0.0->4.0.2) -* Improved documentation. - -Version 1.5.2 -============= - -* Code optionizations. -* New: Documentation is now also provided as Dash_ / Zeal_ docset, downloadable from releases_ at github. - -Version 1.5.1 -============= - -* Fix: `.ServerDbServices.set_replica_mode()` now works correctly. - -Version 1.5.0 -============= - -* Fix: `~firebird.driver.core.create_database()` now use server configuration user/password - if either is not specified in database configuration (like `.connect()`) -* Fix: Problem in `.Server` processing incomplete LINE responses. -* New: `verbint` parameter for `.ServerDbServices3.backup()` and `.ServerDbServices3.restore()` - - This is undocumented Firebird v3 gbak feature. See https://github.com/FirebirdSQL/firebird/issues/808 - for details. It's mutually exclusive with `verbose`, and minimal value is 100. - -Potentially breaking changes ----------------------------- - -* Change in `.ServerDbServices3.restore()`: The `verbose` parameter default value was changed - to `False` to be consistent with `.ServerDbServices3.backup()` -* Change in `.ShutdownMethod`: DENNY_ATTACHMENTS/DENNY_TRANSACTIONS renamed to - DENY_ATTACHMENTS/DENY_TRANSACTIONS. - -Version 1.4.3 -============= - -* Fix: Load driver configuration only when it's successfully read from file(s) -* Fix: Reading service output will fail if line is greater than 64K -* Fix: Avoid division by zero if fetches stats is zero in DatabaseInfoProvider.cache_hit_ratio -* Fix: Rewind buffer with version string after using in EngineVersionProvider -* Fix: Add low-level access to fb_shutdown_callback API function - -Version 1.4.2 -============= - -* New `.ServerConfig` options: `~ServerConfig.encoding` and `~ServerConfig.encoding_errors`. -* New `.connect_server` parameters: `encoding` and `encoding_errors`. -* Requires firebird-base 1.3.1 - -Version 1.4.1 -============= - -* Fixed important bug when iAttachment was not properly released. - -Version 1.4.0 -============= - -Improvements: -------------- - -* Added `role` parameter to `.connect_server` and `~firebird.driver.core.SPB_ATTACH`. -* Added `encoding` parameter to `~firebird.driver.core.SPB_ATTACH` with default value - `ascii` - used to encode `config`, `user`, `password` and `expected_db` values. -* Added `encoding` parameter to `~firebird.driver.core.TPB` with default value `ascii` - - used to encode table names. -* `~firebird.driver.core..DPB` parameter `charset` is now used to determine encoding for - `config`, `user`, `password` and `role` values. -* `.connect_server` has new `encoding` parameter with default value `ascii` that is passed - to new `.Server.encoding` attribute. `.Server.encoding` is used to encode/decode various - string values passed between client and server in parameter buffers (see below), and text - output from services. -* `.ServerInfoProvider` now uses `.Server.encoding` for returned SERVER_VERSION, IMPLEMENTATION, - GET_ENV, GET_ENV_MSG, GET_ENV_LOCK, USER_DBPATH and DBNAME values. -* `.ServerDbServices` now uses `.Server.encoding` for DBNAME, SQL_ROLE_NAME, FILE, SKIP_DATA, - INCLUDE_DATA, INCLUDE_TABLE, EXCLUDE_TABLE, INCLUDE_INDEX, EXCLUDE_INDEX, LINE and - isc_spb_sts_table SPB values. -* `.ServerUserServices` now uses `.Server.encoding` for DBNAME, SQL_ROLE_NAME, USER_NAME, - GROUP_NAME, FIRST_NAME, MIDDLE_NAME, LAST_NAME and PASSWORD (on storage only) SPB values. -* `.ServerTraceServices` now uses `.Server.encoding` for CONFIG SPB value. -* Failed `.Connection.close` should not cause problems on object destruction anymore. -* Failed `.Server.close` should not cause problems on object destruction anymore. - -Backward incompatible changes: ------------------------------- - -* `.tpb` parameter `access` renamed to `access_mode`. -* `.FirebirdWarning` now descends from `UserWarning` instead `Warning`, and is reported - to application via `.warnings.warn` instead raised as exception. -* `.iAttachment_v3` attribute `charset` was renamed to `encoding`. -* `.iXpbBuilder.insert_string` optional parameter `encoding` is now keyword-only. - Parameter also added to `.iXpbBuilder.get_string` method. - -Version 1.3.4 -============= - -* `.FirebirdWarning` is not raised as exception, but reported via `warnings.warn` mechanism. -* User-defined encoding for string parameter and response values exchanged between driver - and Firebird engine. This includes TPB, DPB, SPB and various service values: - - - `~firebird.driver.core.TPB`: New `encoding` constructor parameter & attribute. Used - for `table names` in table reservation. - - `~firebird.driver.core.DPB`: Encoding based on connection charset for `config`, - `user name`, `password` and `role`. - - `~firebird.driver.core..SPB`: New `encoding` constructor parameter & attribute. Used - for `config`, `user name`, `password` and `expected database`. - - Connection-related providers: Encoding based on connection charset. - - Server and Service providers: New `.Server.encoding` attribute. -* Fixed bug in `.ServerDbServices3.get_statistics` when `tables` are specified. - - -Version 1.3.3 -============= - -* Fix unregistered bug: Newly extended interface breaks the driver (affects usability of - the driver with Firebird development versions). -* New exception type `.FirebirdWarning`. From now on, warnings from engine are raised as - `.FirebirdWarning` instead `Warning`. In some future release, warnings will not be raised, - but reported via `warnings.warn` mechanism. - -Version 1.3.2 -============= - -* Fix unregistered bug: iUtil methods removed after FB 4 Beta 2 broke the Int128/TZ handling. -* New context manager `.temp_database`. - -Version 1.3.1 -============= - -* Fix unregistered bug: wrong handling of Firebird 4 string info parameters. - -Version 1.3.0 -============= - -* Fix (#4): exeption returns non ascii-127 symbols. - The error message decode uses `.fbapi.err_encoding` value that is initialized to - `locale.getpreferredencoding`. Also, the decode is now done with `errors="replace"`. -* Fix unregistered bug: wrong handling of milliseconds in TIME and TEMEPSTAMP datatype. -* Sync _VERSION_ value with package version -* Fix unregistered bug: Do not raise exception if accessed `.Statement.plan` is `None`. -* Fix unregistered bug: `.get_statistics()` does not send `tables` correctly. -* Fix annotations. -* `.ServerTraceServices` methods now have return values. -* User name added to `.TraceSession`. -* Fix unregistered bug: `auth_plugin_list` configuration option is ignored -* All methods of `.ServerDbServices3` except 3 related to limbo transactions have new - optional keyword-only parameter `role` that is passed to called utility. -* Function `.connect_server()` has new optional keyword-only parameter `expected_db`, - to access services with non-default security database. - -* Improved Firebird 4 support. - - - Version-specific classes introduced. Internal classes `.DatabaseInfoProvider`, - `.TransactionInfoProvider` and `.ServerDbServices` now implement only Firebird 4 features - and descend from Firebird 3 versions. The proper variant is returned according to - connected server. - - New `.DatabaseConfig` options `session_time_zone`, `set_bind`, `decfloat_round` and - `decfloat_traps`. - - New `~firebird.driver.core.DPB` parameters `session_time_zone`, `set_db_replica`, - `set_bind`, `decfloat_round` and `decfloat_traps`. - - New `session_time_zone` keyword parameter for `.connect()`. - - Added explicit support for READ COMMITTED READ CONSISTENCY isolation (when disabled in - Firebird configuration). - - Support for transactions started at specified snapshot number. - New `.TransactionInfoProvider.snapshot_number` property. - The `~firebird.driver.core.TPB` has new `at_snapshot_number` parameter. - - `.backup()` and `.local_backup()` have new optional keyword-only arguments - `include_data`, `keyhoder`, `keyname` and `crypt`, and `ZIP` value was added to `SrvBackupFlag`. - - `.restore()` and `.local_restore()` have new optional keyword-only - arguments `include_data`, `keyhoder`, `keyname`, `crypt` and `replica_mode`. - - `.nbackup()` has new optional keyword-only parameter `guid`. - - Support for new services. - New methods `.ServerDbServices.nfix_database()` and `.set_replica_mode()`. - - Support for `.Statement.timeout`, and `idle_timeout` and `statement_timeout` in `.Connection.info`. - - New types: `.Features`, `.ReplicaMode`, `.CancelType`, `.DecfloatRound`, `.DecfloatTraps`, - `.ConnectionFlag` and `.EncryptionFlag`. Firebird 4-related values added to some other - enum types. - -Version 1.2.1 -============= - -* Fixed dependency to `firebird-base` (v1.3.0) - -Version 1.2.0 -============= - -* Fix unregistered bug: `sql_dialect` is used instead `db_sql_dialect` in - `~firebird.driver.core.create_database`. -* Fix (#2): error when handling input parameters with value None -* Added `.Server.mode` attribute to allow fetching service output using LINE or TO_EOF method. - Default mode is TO_EOF. - -Version 1.1.0 -============= - -* Important: Support for Firebird 4 TIMEZONE is broken (for FB4 RC1). It will be fixed in - next driver version. -* Build scheme changed to `PEP 517`. -* Various changes to documentation and type hint adjustments. -* Changed: `.DriverConfig.db_defaults` and `.DriverConfig.server_defaults` are now created - as `optional` (introduced by firebird-base 1.2.0), so configuration file does not require - `firebird.db.defaults` and `firebird.server.defaults` sections (even empty). -* Fix: unregistered bug in `InfoProvider`. -* Fix: unregistered bug in `FirebirdAPI` initialization. - -Version 1.0.0 -============= - -* Added support for schema and monitor modules from `firebird-lib`_ package. -* Documentation: adjustments to css. - -Version 0.8.0 -============= - -The driver is no longer *beta*, and is now considered as **stable** for Firebird 3.0 (support for Firebird 4 is still evolving till final release). - -* Documentation, both in code and separate (especially Usage Guide). -* Added support for new FB4 data types in ARRAY fields. -* Refactoring in driver hooks. -* New `.Cursor.call_procedure()` method. -* Refactoring and fixes in Server and its services. - -Version 0.7.0 -============= - -* Added support for new FB4 data types (TIME/TIMESTAMP WITH TIMEZONE, DECFLOAT[16|34] and - extended DECIMAL/NUMERIC via INT128 storage). - -Version 0.6.0 -============= - -* More documentation. -* Initial support for Firebird 4+ (interfaces and other definitions). Includes support for - interface versions. -* `Service` renamed to `Server`. Selected functionality moved to inner objects (relates to - FB4+ support). -* New module: `~firebird.driver.config` - Driver configuration -* New module: `~firebird.driver.interfaces` - Interface wrappers for Firebird new API -* Changed module: `~firebird.driver.types` - - - Interface wrapper moved to separate module - - Buffer managers moved to `~firebird.driver.core` module -* Changed module: `~firebird.driver.core` - - - `connect()`, `create_database()` and `connect_server()` now use driver configuration. - - Simplified/unified transaction isolation specification. - - Emit warnings when objects with allocated Firebird resources are disposed (by Python - GC) without prior call to `close()`. - - Trace instrumentation removed. Use dynamic trace configuration from firebird-base 0.6.0. - - `Connection` and `Transaction` information moved to inner objects accessible via `info` - properties (relates to FB4+ support). - -Version 0.5.0 -============= - -Initial release. - -.. _firebird-lib: https://pypi.org/project/firebird-lib/ -.. _releases: https://github.com/FirebirdSQL/python3-driver/releases -.. _Dash: https://kapeli.com/dash -.. _Zeal: https://zealdocs.org/ diff --git a/docs/conf.py b/docs/conf.py deleted file mode 100644 index a5a4015..0000000 --- a/docs/conf.py +++ /dev/null @@ -1,211 +0,0 @@ -# Configuration file for the Sphinx documentation builder. -# -# This file only contains a selection of the most common options. For a full -# list see the documentation: -# https://www.sphinx-doc.org/en/master/usage/configuration.html - -# -- Path setup -------------------------------------------------------------- - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -# -# import os -# import sys -# sys.path.insert(0, os.path.abspath('.')) - -import sphinx_bootstrap_theme -from firebird.driver import __VERSION__ - -# -- Project information ----------------------------------------------------- - -project = 'firebird-driver' -copyright = '2020-present, The Firebird Project' -author = 'Pavel Císař' - -# The short X.Y version -version = __VERSION__ - -# The full version, including alpha/beta/rc tags -release = __VERSION__ - - -# -- General configuration --------------------------------------------------- - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - 'sphinx.ext.intersphinx', - 'sphinx.ext.autodoc', - 'sphinx.ext.napoleon', - 'sphinx.ext.viewcode', - 'sphinx.ext.autosectionlabel', - #'sphinx_autodoc_typehints', - 'sphinx.ext.todo', - #'sphinx.ext.coverage', -] - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -# -# source_suffix = ['.rst', '.md'] -source_suffix = '.txt' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -# This pattern also affects html_static_path and html_extra_path. -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', 'requirements.txt'] - -default_role = 'py:obj' - -# -- Options for HTML output ------------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -# -#html_theme = 'alabaster' - -html_theme = "bootstrap" -html_theme_path = sphinx_bootstrap_theme.get_html_theme_path() - -# bootstrap theme config - -# (Optional) Logo. Should be small enough to fit the navbar (ideally 24x24). -# Path should be relative to the ``_static`` files directory. -#html_logo = "my_logo.png" - -# Theme options are theme-specific and customize the look and feel of a -# theme further. -html_theme_options = { - # Navigation bar title. (Default: ``project`` value) - #'navbar_title': "Firebird-driver", - - # Tab name for entire site. (Default: "Site") - 'navbar_site_name': "Content", - - # A list of tuples containing pages or urls to link to. - # Valid tuples should be in the following forms: - # (name, page) # a link to a page - # (name, "/aa/bb", 1) # a link to an arbitrary relative url - # (name, "http://example.com", True) # arbitrary absolute url - # Note the "1" or "True" value above as the third argument to indicate - # an arbitrary url. - 'navbar_links': [ - ("Usage Guide", "usage-guide"), - ("Reference", "reference"), - ("Index", "genindex"), - ], - - # Render the next and previous page links in navbar. (Default: true) - 'navbar_sidebarrel': False, - - # Render the current pages TOC in the navbar. (Default: true) - #'navbar_pagenav': True, - - # Tab name for the current pages TOC. (Default: "Page") - #'navbar_pagenav_name': "Page", - - # Global TOC depth for "site" navbar tab. (Default: 1) - # Switching to -1 shows all levels. - 'globaltoc_depth': 3, - - # Include hidden TOCs in Site navbar? - # - # Note: If this is "false", you cannot have mixed ``:hidden:`` and - # non-hidden ``toctree`` directives in the same page, or else the build - # will break. - # - # Values: "true" (default) or "false" - 'globaltoc_includehidden': "true", - - # HTML navbar class (Default: "navbar") to attach to
element. - # For black navbar, do "navbar navbar-inverse" - 'navbar_class': "navbar navbar-inverse", - - # Fix navigation bar to top of page? - # Values: "true" (default) or "false" - 'navbar_fixed_top': "true", - - # Location of link to source. - # Options are "nav" (default), "footer" or anything else to exclude. - 'source_link_position': "none", - - # Bootswatch (http://bootswatch.com/) theme. - # - # Options are nothing (default) or the name of a valid theme - # such as "cosmo" or "sandstone". - # - # The set of valid themes depend on the version of Bootstrap - # that's used (the next config option). - # - # Currently, the supported themes are: - # - Bootstrap 2: https://bootswatch.com/2 - # - Bootstrap 3: https://bootswatch.com/3 - #'bootswatch_theme': "united", # cerulean, flatly, lumen, materia, united, yeti - 'bootswatch_theme': "cerulean", - - # Choose Bootstrap version. - # Values: "3" (default) or "2" (in quotes) - 'bootstrap_version': "2", -} - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] - - -# -- Extension configuration ------------------------------------------------- - -autosectionlabel_prefix_document = True - -# Autodoc options -# --------------- -autodoc_default_options = { - 'content': 'both', - 'members': True, - 'member-order': 'groupwise', - 'undoc-members': True, - 'exclude-members': '__weakref__', - 'show-inheritance': True, - 'no-inherited-members': True, - 'no-private-members': True, -} -set_type_checking_flag = True -autodoc_class_signature = 'mixed' -always_document_param_types = True -autodoc_typehints = 'both' # default 'signature' -autodoc_typehints_format = 'short' -autodoc_typehints_description_target = 'all' - -# Napoleon options -# ---------------- -napoleon_include_init_with_doc = True -napoleon_include_private_with_doc = True -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = True -napoleon_use_admonition_for_references = True -napoleon_use_ivar = False -napoleon_use_rtype = True -napoleon_use_param = True -napoleon_use_keyword = True -napoleon_attr_annotations = True -napoleon_preprocess_types = True - -# -- Options for intersphinx extension --------------------------------------- - -# intersphinx -intersphinx_mapping = {'python': ('https://docs.python.org/3', None), - 'base': ('https://firebird-base.rtfd.io/en/latest', None), - 'lib': ('https://firebird-lib.rtfd.io/en/latest', None), - } - -# -- Options for todo extension ---------------------------------------------- - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True diff --git a/docs/_static/fb-favicon.png b/docs/docs/assets/fb-favicon.png similarity index 100% rename from docs/_static/fb-favicon.png rename to docs/docs/assets/fb-favicon.png diff --git a/docs/docs/changelog.md b/docs/docs/changelog.md new file mode 120000 index 0000000..699cc9e --- /dev/null +++ b/docs/docs/changelog.md @@ -0,0 +1 @@ +../../CHANGELOG.md \ No newline at end of file diff --git a/docs/docs/getting-started.md b/docs/docs/getting-started.md new file mode 100644 index 0000000..34e27e6 --- /dev/null +++ b/docs/docs/getting-started.md @@ -0,0 +1,334 @@ + +# Getting Started + +## Installation + +Firebird-driver is written as pure-Python module (requires Python 3.11+) on top of +Firebird client library (fbclient.so/dll) using [ctypes](http://docs.python.org/library/ctypes.html). Driver supports Firebird version +3.0 and higher. + +Firebird-driver is distributed as a Python package and the preferred installation +method is via [pip](https://pypi.org/project/pip/) tool. + +## Installation from [PYPI](https://pypi.org/) + +Run pip: + +```text +$ pip install firebird-driver + +``` +## Quick-start Guide + +This brief tutorial aims to get the reader started by demonstrating elementary usage of +Firebird-driver. It is not a comprehensive Python Database API tutorial, nor is it +comprehensive in its coverage of anything else. + +The numerous advanced features of Firebird-driver are covered in another section of this +documentation, which is not in a tutorial format, though it is replete with examples. + +## Driver configuration + +The driver uses configuration built on top of [configuration system](https://firebird-base.readthedocs.io/en/latest/config/) +provided by [firebird-base](https://firebird-base.rtfd.io) package. In addition to global settings, the configuration +also includes the definition of connection parameters to Firebird servers and databases. + +The default configuration connects to embedded server using direct/local connection method. +To access remote servers and databases (or local ones through remote protocols), it's +necessary to adjust default configuration, or `register` them in configuration manager. + +You can manipulate the configuration objects directly, or load configuration from files or +strings (in `.ini-style` `ConfigParser` format). + +## Connecting to a Database + +**Example 1:** + +A simple database connection is typically established with code such as this: + +```python +from firebird.driver import connect + +# Attach to 'employee' database/alias using embedded server connection +con = connect('employee', user='sysdba', password='masterkey') + +# Attach to 'employee' database/alias using local server connection +from firebird.driver import driver_config +driver_config.server_defaults.host.value = 'localhost' +con = connect('employee', user='sysdba', password='masterkey') + +# Set 'user' and 'password' via configuration +driver_config.server_defaults.user.value = 'SYSDBA' +driver_config.server_defaults.password.value = 'masterkey' +con = connect('employee') + +``` + +**Example 2:** + +A database connection typically uses specific configuration, and is established with code +such as this: + +```python +from firebird.driver import connect, driver_config + +# Register Firebird server +srv_cfg = """[local] +host = localhost +user = SYSDBA +password = masterkey +""" +driver_config.register_server('local', srv_cfg) + +# Register database +db_cfg = """[employee] +server = local +database = employee.fdb +protocol = inet +charset = utf8 +""" +driver_config.register_database('employee', db_cfg) + +# Attach to 'employee' database +con = connect('employee') + +``` + +!!! note + + Some parameters like 'user' and 'password' could be overridden with keyword parameters. + Few parameters like 'crypt_callback' or 'no_db_triggers' could be specified **ONLY** + as keyword arguments. + +## Creating a Database + +A database is created using `~firebird.driver.core.create_database()` function. +Like `~firebird.driver.core.connect()`, this function uses configuration for specification of +database parameters like page size, sweep interval etc. + +## Executing SQL Statements + +For this section, suppose we have a table defined and populated by the following SQL code: + +```sql +create table languages +( + name varchar(20), + year_released integer +); + +insert into languages (name, year_released) values ('C', 1972); +insert into languages (name, year_released) values ('Python', 1991); + +``` + +**Example 1** + +This example shows the *simplest* way to print the entire contents of +the `languages` table: + +```python +from firebird.driver import connect + +con = connect('test.fdb', user='sysdba', password='masterkey') + +# Create a Cursor object that operates in the context of Connection con: +cur = con.cursor() + +# Execute the SELECT statement: +cur.execute("select * from languages order by year_released") + +# Retrieve all rows as a sequence and print that sequence: +print(cur.fetchall()) + +``` + +Sample output: + +```python +[('C', 1972), ('Python', 1991)] + +``` + +**Example 2** + +Here's another trivial example that demonstrates various ways of fetching a single row at a time from a `SELECT`-cursor: + +```python +from firebird.driver import connect + +con = connect('test.fdb', user='sysdba', password='masterkey') + +cur = con.cursor() +SELECT = "select name, year_released from languages order by year_released" + +# 1. Iterate over the rows available from the cursor, unpacking the +# resulting sequences to yield their elements (name, year_released): +cur.execute(SELECT) +for (name, year_released) in cur: + print(f'{name} has been publicly available since {year_released}.') + +# 2. Equivalently: +cur.execute(SELECT) +for row in cur: + print(f'{row[0]} has been publicly available since {row[1]}.') + +``` + +Sample output: + +```python +C has been publicly available since 1972. +Python has been publicly available since 1991. +C has been publicly available since 1972. +Python has been publicly available since 1991. +C has been publicly available since 1972. +Python has been publicly available since 1991. + +``` + +**Example 3** + +The following program is a simplistic table printer (applied in this example to `languages`): + +```python +from firebird.driver import connect, DESCRIPTION_NAME, DESCRIPTION_DISPLAY_SIZE + +TABLE_NAME = 'languages' +SELECT = f'select * from {TABLE_NAME} order by year_released' + +con = connect('test.fdb', user='sysdba', password='masterkey') + +cur = con.cursor() +cur.execute(SELECT) + +# Print a header. +for fieldDesc in cur.description: + print(fieldDesc[DESCRIPTION_NAME].ljust(fieldDesc[DESCRIPTION_DISPLAY_SIZE]), end='') +print() # Finish the header with a newline. +print('-' * 78) + +# For each row, print the value of each field left-justified within +# the maximum possible width of that field. +fieldIndices = range(len(cur.description)) +for row in cur: + for fieldIndex in fieldIndices: + fieldValue = str(row[fieldIndex]) + fieldMaxWidth = cur.description[fieldIndex][DESCRIPTION_DISPLAY_SIZE] + + print(fieldValue.ljust(fieldMaxWidth), end='') + + print() # Finish the row with a newline. + + +``` + +Sample output: + +```python +NAME YEAR_RELEASED +------------------------------------------------------------------------------ +C 1972 +Python 1991 + + +``` + +**Example 4** + +Let's insert more languages: + +```python +from firebird.driver import connect + +con = connect('test.fdb', user='sysdba', password='masterkey') + +cur = con.cursor() + +newLanguages = [ + ('Lisp', 1958), + ('Dylan', 1995), + ] + +cur.executemany("insert into languages (name, year_released) values (?, ?)", + newLanguages + ) + +# The changes will not be saved unless the transaction is committed explicitly: +con.commit() + + +``` + +Note the use of a *parameterized* SQL statement above. When dealing with repetitive +statements, this is much faster and less error-prone than assembling each SQL statement +manually. (You can read more about parameterized SQL statements in the section on +[Prepared Statements](usage-guide.md#prepared-statements).) + +After running Example 4, the table printer from Example 3 would print: + +```python +NAME YEAR_RELEASED +------------------------------------------------------------------------------ +Lisp 1958 +C 1972 +Python 1991 +Dylan 1995 + + +``` + +## Calling Stored Procedures + +Firebird supports stored procedures written in a proprietary procedural SQL language. +Firebird stored procedures can have *input* parameters and/or *output* parameters. Some +databases support *input/output* parameters, where the same parameter is used for both +input and output; Firebird does not support this. + +It is important to distinguish between procedures that *return a result set* and procedures +that *populate and return their output parameters exactly once*. Conceptually, the latter +"return their output parameters" like a Python function, whereas the former "yield result +rows" like a Python generator. + +Firebird's *server-side* procedural SQL syntax makes no such distinction, but *client-side* +SQL code (and C API code) must. A result set is retrieved from a stored procedure by +`SELECT`-ing from the procedure, whereas output parameters are retrieved with an +`EXECUTE PROCEDURE` statement. + +To *retrieve a result set* from a stored procedure with Firebird-driver, use code such as this: + +```python +cur.execute("select output1, output2 from the_proc(?, ?)", (input1, input2)) + +# Ordinary fetch code here, such as: +for row in cur: + ... # process row + +con.commit() # If the procedure had any side effects, commit them. + + +``` + +To *execute* a stored procedure and *access its output parameters*, use code such as this: + +```python +cur.callproc("the_proc", (input1, input2)) + +# If there are output parameters, retrieve them as though they were the +# first row of a result set. For example: +outputParams = cur.fetchone() + +con.commit() # If the procedure had any side effects, commit them. + + +``` + +This latter is not very elegant; it would be preferable to access the procedure's output +parameters as the return value of `Cursor.callproc()`. The Python DB API specification +requires the current behavior, however. + +[setuptools]: https://pypi.org/project/setuptools/ +[PYPI]: https://pypi.org/ +[ctypes]: http://docs.python.org/library/ctypes.html +[pip]: https://pypi.org/project/pip/ +[firebird-base]: https://firebird-base.rtfd.io diff --git a/docs/docs/index.md b/docs/docs/index.md new file mode 100644 index 0000000..5361efa --- /dev/null +++ b/docs/docs/index.md @@ -0,0 +1,49 @@ + +# The Python driver for Firebird + +The `firebird-driver` package provides official [Python Database API 2.0](http://www.python.org/dev/peps/pep-0249/)-compliant driver +for the open source relational database [Firebird](http://www.firebirdsql.org) ®. In addition to the minimal feature +set of the standard Python DB API, this driver also exposes the new (interface-based) client +API introduced in Firebird 3, and number of additional extensions and enhancements for +convenient use of Firebird RDBMS. + +This documentation set is not a tutorial on SQL or Firebird; rather, it is a topical +presentation of driver's feature set, with example code to demonstrate basic usage patterns. +For detailed information about Firebird features, see the +[Firebird documentation](http://www.firebirdsql.org/en/documentation/), and especially +the excellent [The Firebird Book](http://www.ibphoenix.com/products/books/firebird_book) +written by Helen Borrie and published by [IBPhoenix](http://www.ibphoenix.com). + +!!! info + [firebird-lib](https://pypi.org/project/firebird-lib/) package for optional extensions to this driver. + +!!! note + Requires Python 3.11+ + +!!! tip + You can download docset for [Dash](https://kapeli.com/dash) (MacOS) or [Zeal](https://zealdocs.org/) (Windows / Linux) documentation + + readers from [releases](https://github.com/FirebirdSQL/python3-driver/releases) at github. + +## Content + +- [Getting Started](getting-started.md) +- [Usage Guide](usage-guide.md) +- [Python Db Api Compliance](python-db-api-compliance.md) +- [Reference](ref-main.md) +- [Changelog](changelog.md) +- [License](license.md) + +Driver development is sponsored by [IBPhoenix](http://www.ibphoenix.com). + +[IBPhoenix]: http://www.ibphoenix.com +[Python]: http://python.org +[Python Database API 2.0]: http://www.python.org/dev/peps/pep-0249/ +[Firebird]: http://www.firebirdsql.org +[under]: http://www.firebirdsql.org/en/devel-python-driver/ +[Firebird Project]: http://www.firebirdsql.org +[IBPhoenix]: http://www.ibphoenix.com +[firebird-lib]: https://pypi.org/project/firebird-lib/ +[releases]: https://github.com/FirebirdSQL/python3-driver/releases +[Dash]: https://kapeli.com/dash +[Zeal]: https://zealdocs.org/ diff --git a/docs/docs/license.md b/docs/docs/license.md new file mode 100644 index 0000000..0e9c6e6 --- /dev/null +++ b/docs/docs/license.md @@ -0,0 +1,23 @@ +# License + +MIT License + +Copyright (c) 2020 The Firebird Project (www.firebirdsql.org) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/docs/python-db-api-compliance.txt b/docs/docs/python-db-api-compliance.md similarity index 81% rename from docs/python-db-api-compliance.txt rename to docs/docs/python-db-api-compliance.md index 0a1a64d..2c1ec03 100644 --- a/docs/python-db-api-compliance.txt +++ b/docs/docs/python-db-api-compliance.md @@ -1,22 +1,17 @@ -########################## -Compliance to PyDB API 2.0 -########################## +# Compliance to PyDB API 2.0 -.. currentmodule:: firebird.driver Full text of Python Database API 2.0 (PEP 249) is available at -`http://www.python.org/dev/peps/pep-0249/ `__ +[http://www.python.org/dev/peps/pep-0249/](http://www.python.org/dev/peps/pep-0249/) -Unsupported Optional Features -============================= +## Unsupported Optional Features `Cursor.nextset` This method is not implemented because the database engine does not support opening multiple result sets simultaneously with a single cursor. -Supported Optional Features -=========================== +## Supported Optional Features - `Connection.Error`, `Connection.ProgrammingError`, etc. @@ -27,8 +22,7 @@ Supported Optional Features This read-only attribute return a reference to the Connection object on which the cursor was created. -Nominally Supported Optional Features -===================================== +## Nominally Supported Optional Features `.Cursor` @@ -48,8 +42,7 @@ Nominally Supported Optional Features Although this method is present, it does nothing, as allowed by the spec. -Caveats -======= +## Caveats Firebird-driver offers a large feature set beyond the minimal requirements of the Python DB API. This section attempts to document only those @@ -84,25 +77,27 @@ features that overlap with the DB API. of all `description` elements are defined by the DB API spec; these constants are provided merely for convenience. - .. sourcecode:: python + ```python + DESCRIPTION_NAME + DESCRIPTION_TYPE_CODE + DESCRIPTION_DISPLAY_SIZE + DESCRIPTION_INTERNAL_SIZE + DESCRIPTION_PRECISION + DESCRIPTION_SCALE + DESCRIPTION_NULL_OK - DESCRIPTION_NAME - DESCRIPTION_TYPE_CODE - DESCRIPTION_DISPLAY_SIZE - DESCRIPTION_INTERNAL_SIZE - DESCRIPTION_PRECISION - DESCRIPTION_SCALE - DESCRIPTION_NULL_OK + ``` Here is an example of accessing the *name* of the first field in the `description` of cursor `cur`: - .. sourcecode:: python + ```python + nameOfFirstField = cur.description[0][firebird.driver.DESCRIPTION_NAME] - nameOfFirstField = cur.description[0][firebird.driver.DESCRIPTION_NAME] + ``` For more information, see the documentation of Cursor.description in - the `DB API Specification `__. + the [DB API Specification](https://peps.python.org/pep-0249/). `~.Cursor.rowcount` @@ -124,6 +119,6 @@ features that overlap with the DB API. performed on the cursor or the rowcount of the last operation is not determinable by the interface". - .. note:: + !!! note - This attribute is just an alias for `.Cursor.affected_rows` property. + This attribute is just an alias for `.Cursor.affected_rows` property. diff --git a/docs/ref-config.txt b/docs/docs/ref-config.md similarity index 61% rename from docs/ref-config.txt rename to docs/docs/ref-config.md index 7fe37f3..83324c2 100644 --- a/docs/ref-config.txt +++ b/docs/docs/ref-config.md @@ -1,9 +1,5 @@ -.. module:: firebird.driver.config - :synopsis: Driver configuration -====================== -firebird.driver.config -====================== +# firebird.driver.config This module defines the configuration system for the firebird-driver. It uses an INI-style format managed via the `DriverConfig` class, which @@ -14,15 +10,14 @@ Configuration can be loaded from files, strings, or dictionaries, and supports environment variable interpolation. The primary interaction point is usually the global `driver_config` instance. -Classes -======= +## Classes -.. autoclass:: DriverConfig -.. autoclass:: ServerConfig -.. autoclass:: DatabaseConfig +::: firebird.driver.config.DriverConfig -Globals -======= +::: firebird.driver.config.ServerConfig -.. autodata:: driver_config - :no-value: +::: firebird.driver.config.DatabaseConfig + +## Globals + +::: firebird.driver.config.driver_config diff --git a/docs/docs/ref-core.md b/docs/docs/ref-core.md new file mode 100644 index 0000000..0a5f53a --- /dev/null +++ b/docs/docs/ref-core.md @@ -0,0 +1,109 @@ + +# firebird.driver.core + +This is the main code module of the Firebird driver. + +## Constants and variables + +### C integer limit constants + + - SHRT_MIN + - SHRT_MAX + - USHRT_MAX + - INT_MIN + - INT_MAX + - UINT_MAX + - LONG_MIN + - LONG_MAX + +### Translation dictionaries + +::: firebird.driver.core.CHARSET_MAP + +### Other constants and variables + +::: firebird.driver.core.MAX_BLOB_SEGMENT_SIZE + +::: firebird.driver.core.FS_ENCODING + +::: firebird.driver.core._master + +::: firebird.driver.core._util + +::: firebird.driver.core.TIMEOUT + +## Context managers + +::: firebird.driver.core.transaction + +::: firebird.driver.core.temp_database + +## Functions + +::: firebird.driver.core.connect + +::: firebird.driver.core.create_database + +::: firebird.driver.core.connect_server + +::: firebird.driver.core.tpb + +## Managers for parameter buffers + +::: firebird.driver.core.TPB + +::: firebird.driver.core.DPB + +::: firebird.driver.core.SPB_ATTACH + +::: firebird.driver.core.Buffer + +::: firebird.driver.core.CBuffer + +## Classes + +::: firebird.driver.core.Connection + +::: firebird.driver.core.TransactionManager + +::: firebird.driver.core.DistributedTransactionManager + +::: firebird.driver.core.Statement + +::: firebird.driver.core.Cursor + +::: firebird.driver.core.Server + +::: firebird.driver.core.ServerServiceProvider + +::: firebird.driver.core.ServerDbServices3 + +::: firebird.driver.core.ServerDbServices + +::: firebird.driver.core.ServerUserServices + +::: firebird.driver.core.ServerTraceServices + +::: firebird.driver.core.InfoProvider + +::: firebird.driver.core.DatabaseInfoProvider3 + +::: firebird.driver.core.DatabaseInfoProvider + +::: firebird.driver.core.TransactionInfoProvider3 + +::: firebird.driver.core.TransactionInfoProvider + +::: firebird.driver.core.StatementInfoProvider3 + +::: firebird.driver.core.StatementInfoProvider + +::: firebird.driver.core.ServerInfoProvider + +::: firebird.driver.core.EventCollector + +::: firebird.driver.core.EventBlock + +::: firebird.driver.core.BlobReader + +::: firebird.driver.core.EngineVersionProvider diff --git a/docs/docs/ref-fbapi.md b/docs/docs/ref-fbapi.md new file mode 100644 index 0000000..15ac470 --- /dev/null +++ b/docs/docs/ref-fbapi.md @@ -0,0 +1,551 @@ + +# firebird.driver.fbapi + +This module contains low-level [ctypes](https://docs.python.org/3/library/ctypes.html) interface to +Firebird client library (`fbclient.so/dll`). + +## Constants + +### Type codes + + - SQL_TEXT + - SQL_VARYING + - SQL_SHORT + - SQL_LONG + - SQL_FLOAT + - SQL_DOUBLE + - SQL_D_FLOAT + - SQL_TIMESTAMP + - SQL_BLOB + - SQL_ARRAY + - SQL_QUAD + - SQL_TYPE_TIME + - SQL_TYPE_DATE + - SQL_INT64 + - SQL_BOOLEAN + - SQL_NULL + - SUBTYPE_NUMERIC + - SUBTYPE_DECIMAL + +### Internal type codes (for example used by ARRAY descriptor) + + - blr_text + - blr_text2 + - blr_short + - blr_long + - blr_quad + - blr_float + - blr_double + - blr_d_float + - blr_timestamp + - blr_varying + - blr_varying2 + - blr_blob + - blr_cstring + - blr_cstring2 + - blr_blob_id + - blr_sql_date + - blr_sql_time + - blr_int64 + - blr_blob2 + - blr_domain_name + - blr_domain_name2 + - blr_not_nullable + - blr_column_name + - blr_column_name2 + - blr_bool + - blr_dec64 + - blr_dec128 + - blr_dec_fixed + - blr_sql_time_tz + - blr_timestamp_tz + - blr_ex_time_tz + - blr_ex_timestamp_tz + +## Types + +::: firebird.driver.fbapi.Int + options: + show_bases: false + +::: firebird.driver.fbapi.IntPtr + options: + show_bases: false + +::: firebird.driver.fbapi.Int64 + options: + show_bases: false + +::: firebird.driver.fbapi.Int64Ptr + options: + show_bases: false + +::: firebird.driver.fbapi.QWord + options: + show_bases: false + +::: firebird.driver.fbapi.STRING + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_LONG + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_LONG_PTR + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_ULONG + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_SHORT + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_USHORT + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_UCHAR + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_INT64 + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_UINT64 + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_DATE + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_TIME + options: + show_bases: false + +::: firebird.driver.fbapi.FB_DEC16 + options: + show_bases: false + +::: firebird.driver.fbapi.FB_DEC16Ptr + options: + show_bases: false + +::: firebird.driver.fbapi.FB_DEC34 + options: + show_bases: false + +::: firebird.driver.fbapi.FB_DEC34Ptr + options: + show_bases: false + +::: firebird.driver.fbapi.FB_I128 + options: + show_bases: false + +::: firebird.driver.fbapi.FB_I128Ptr + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_QUAD + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_QUAD_PTR + options: + show_bases: false + +::: firebird.driver.fbapi.FB_API_HANDLE + options: + show_bases: false + +::: firebird.driver.fbapi.FB_API_HANDLE_PTR + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_STATUS + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_STATUS_PTR + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_STATUS_ARRAY + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_STATUS_ARRAY_PTR + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_ARRAY_BOUND + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_ARRAY_DESC + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_ARRAY_DESC_PTR + options: + show_bases: false + +::: firebird.driver.fbapi.RESULT_VECTOR + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_TIME_TZ + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_TIME_TZ_EX + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_TIMESTAMP + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_TIMESTAMP_TZ + options: + show_bases: false + +::: firebird.driver.fbapi.ISC_TIMESTAMP_TZ_EX + options: + show_bases: false + +::: firebird.driver.fbapi.TraceCounts + options: + show_bases: false + +::: firebird.driver.fbapi.PerformanceInfo + options: + show_bases: false + +## Variables + +::: firebird.driver.fbapi.err_encoding + +## Functions + +::: firebird.driver.fbapi.has_api + +::: firebird.driver.fbapi.load_api + +::: firebird.driver.fbapi.get_api + +## Classes + +::: firebird.driver.fbapi.FirebirdAPI + +## Firebird API Interface definitions + +::: firebird.driver.fbapi.IVersioned_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IVersioned_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IReferenceCounted_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IReferenceCounted_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IDisposable_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IDisposable_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IStatus_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IStatus_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IMaster_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IMaster_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IPluginBase_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IPluginBase_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IPluginSet_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IPluginSet_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IConfigEntry_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IConfigEntry_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IConfig_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IConfig_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IFirebirdConf_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IFirebirdConf_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IPluginManager_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IPluginManager_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IConfigManager_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IConfigManager_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IEventCallback_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IEventCallback_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IBlob_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IBlob_struct + options: + show_bases: false + +::: firebird.driver.fbapi.ITransaction_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.ITransaction_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IMessageMetadata_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IMessageMetadata_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IMetadataBuilder_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IMetadataBuilder_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IResultSet_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IResultSet_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IStatement_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IStatement_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IBatch_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IBatch_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IBatchCompletionState_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IBatchCompletionState_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IRequest_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IRequest_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IEvents_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IEvents_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IAttachment_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IAttachment_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IService_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IService_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IProvider_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IProvider_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IDtcStart_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IDtcStart_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IDtc_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IDtc_struct + options: + show_bases: false + +::: firebird.driver.fbapi.ICryptKeyCallback_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.ICryptKeyCallback_struct + options: + show_bases: false + +::: firebird.driver.fbapi.ITimer_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.ITimer_struct + options: + show_bases: false + +::: firebird.driver.fbapi.ITimerControl_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.ITimerControl_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IVersionCallback_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IVersionCallback_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IUtil_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IUtil_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IOffsetsCallback_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IOffsetsCallback_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IXpbBuilder_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IXpbBuilder_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IDecFloat16_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IDecFloat16_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IDecFloat34_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IDecFloat34_struct + options: + show_bases: false + +::: firebird.driver.fbapi.IInt128_VTable + options: + show_bases: false + +::: firebird.driver.fbapi.IInt128_struct + options: + show_bases: false diff --git a/docs/ref-hooks.txt b/docs/docs/ref-hooks.md similarity index 56% rename from docs/ref-hooks.txt rename to docs/docs/ref-hooks.md index 1d24b8e..af9c709 100644 --- a/docs/ref-hooks.txt +++ b/docs/docs/ref-hooks.md @@ -1,9 +1,5 @@ -.. module:: firebird.driver.hooks - :synopsis: Drivers hooks -===================== -firebird.driver.hooks -===================== +# firebird.driver.hooks This module contains firebird-driver hooks. Uses hook mechanism from firebird-base package. @@ -11,9 +7,10 @@ Imports from `firebird.base.hooks`: `~firebird.base.hooks.register_class`, `~firebird.base.hooks.get_callbacks`, `~firebird.base.hooks.add_hook` and `~firebird.base.hooks.hook_manager`. -Enums -===== +## Enums -.. autoclass:: APIHook -.. autoclass:: ConnectionHook -.. autoclass:: ServerHook +::: firebird.driver.hooks.APIHook + +::: firebird.driver.hooks.ConnectionHook + +::: firebird.driver.hooks.ServerHook diff --git a/docs/docs/ref-intf.md b/docs/docs/ref-intf.md new file mode 100644 index 0000000..7fb9430 --- /dev/null +++ b/docs/docs/ref-intf.md @@ -0,0 +1,180 @@ + +# firebird.driver.interfaces + +This module contains interface wrappers for Firebird new API. + +!!! important + + 1. Firebird OO API interfaces use inheritance, i.e. they could be inherited from other + interface. In fact, all interfaces returned by Firebird are inherited from `IVersioned` + interface. + + 2. Firebird OO API interfaces are versioned. Any addition to particular interface + increases its version number. Application developers are responsible to check the + version of returned interface to verify that it supports methods they want to use. + + If you want to use Firebird OO API interfaces directly in you application, read next + section very carefuly. + +In Python driver, interfaces are represented as instances of interface wrapper classes +that expose the methods provided by particular Firebird interface version. The wrapper +class hierarchy thus represent not only inheritabce between Firebird interfaces, but also +between versions of particular Firebird interface. + +Because all interfaces returned by Firebird are inherited from `IVersioned` interface, +all wrapper classes have `VERSION` class attribute that contain version number of wrapped +interface. + +Each Firebird interface has it's "canonical" Python wrapper with coresponding name. For +example interface `IService` has wrapper class `.iService`. However, if there are multiple +public versions of Firebird interface, there are multiple wrapper classes for each published +interface version (interim, non-public versions used during Firebird development are skipped). +These wrapper classes have names based on their canonical name with suffix that represent +the interface version they wrap. It means that canonical wrapper **always** represents +the highest interface version. + +Whenever Firebird interface is returned from Firebird OO API call, it's wrapped to its +Python wrapper class according to interface type and version. The Python driver ensures +that correct wrapper class is used according to returned interface version. + +However, this architecture has several important consequences: + +1. The interface wrapper classes may change between driver releases as new interface versions + are introduced. For example, driver versions up to 1.5.2 had only canonical `.iService` + (version 3), but in version 1.6.0 it was renamed to `.iService_v3`, new wrappers + `.iService_v4` and (new canonical) `.iService` (version 5) were added. +2. Instead using `isinstance` to check interface versions, you should always use + `VERSION` attribute on wrapper class instance. + + +## Metaclasses + +::: firebird.driver.interfaces.iVersionedMeta + +## Firebird API Interface wrappers + +### Base interfaces +::: firebird.driver.interfaces.iVersioned + +::: firebird.driver.interfaces.iReferenceCounted + +::: firebird.driver.interfaces.iDisposable + +::: firebird.driver.interfaces.iStatus + +::: firebird.driver.interfaces.iPluginBase + +::: firebird.driver.interfaces.iMaster + +### Configuration +::: firebird.driver.interfaces.iConfigEntry + +::: firebird.driver.interfaces.iConfig + +::: firebird.driver.interfaces.iFirebirdConf_v3 + +::: firebird.driver.interfaces.iFirebirdConf + +::: firebird.driver.interfaces.iConfigManager_v2 + +::: firebird.driver.interfaces.iConfigManager + +### Database and service attachments +::: firebird.driver.interfaces.iProvider + +::: firebird.driver.interfaces.iAttachment_v3 + +::: firebird.driver.interfaces.iAttachment_v4 + +::: firebird.driver.interfaces.iAttachment + +::: firebird.driver.interfaces.iService_v3 + +::: firebird.driver.interfaces.iService_v4 + +::: firebird.driver.interfaces.iService + +::: firebird.driver.interfaces.iXpbBuilder + +### Blobs +::: firebird.driver.interfaces.iBlob_v3 + +::: firebird.driver.interfaces.iBlob + +### Transactions +::: firebird.driver.interfaces.iTransaction_v3 + +::: firebird.driver.interfaces.iTransaction + +::: firebird.driver.interfaces.iDtcStart + +::: firebird.driver.interfaces.iDtc + +### Metadata +::: firebird.driver.interfaces.iMessageMetadata_v3 + +::: firebird.driver.interfaces.iMessageMetadata + +::: firebird.driver.interfaces.iMetadataBuilder_v3 + +::: firebird.driver.interfaces.iMetadataBuilder + +### SQL execution +::: firebird.driver.interfaces.iStatement_v3 + +::: firebird.driver.interfaces.iStatement_v4 + +::: firebird.driver.interfaces.iStatement + +::: firebird.driver.interfaces.iResultSet_v3 + +::: firebird.driver.interfaces.iResultSet + +::: firebird.driver.interfaces.iBatch_v3 + +::: firebird.driver.interfaces.iBatch + +::: firebird.driver.interfaces.iBatchCompletionState + +### Events +::: firebird.driver.interfaces.iEvents_v3 + +::: firebird.driver.interfaces.iEvents + +### Utilities +::: firebird.driver.interfaces.iTimerControl + +::: firebird.driver.interfaces.iUtil_v2 + +::: firebird.driver.interfaces.iUtil + +::: firebird.driver.interfaces.iDecFloat16 + +::: firebird.driver.interfaces.iDecFloat34 + +::: firebird.driver.interfaces.iInt128 + +### Other +::: firebird.driver.interfaces.iPluginManager + +::: firebird.driver.interfaces.iRequest_v3 + +::: firebird.driver.interfaces.iRequest + +## Interface implementations + +::: firebird.driver.interfaces.iVersionedImpl + +::: firebird.driver.interfaces.iReferenceCountedImpl + +::: firebird.driver.interfaces.iDisposableImpl + +::: firebird.driver.interfaces.iVersionCallbackImpl + +::: firebird.driver.interfaces.iCryptKeyCallbackImpl + +::: firebird.driver.interfaces.iOffsetsCallbackImp + +::: firebird.driver.interfaces.iEventCallbackImpl + +::: firebird.driver.interfaces.iTimerImpl diff --git a/docs/ref-main.txt b/docs/docs/ref-main.md similarity index 77% rename from docs/ref-main.txt rename to docs/docs/ref-main.md index 1ccb8cf..db108b0 100644 --- a/docs/ref-main.txt +++ b/docs/docs/ref-main.md @@ -1,31 +1,19 @@ -===================== -Main driver namespace -===================== +# Main driver namespace -.. module:: firebird.driver - :synopsis: Python 3+ Database API 2.0 Compliant driver for Firebird 3+ -Constants -========= +## Constants -.. autodata:: __VERSION__ - :no-value: +::: firebird.driver.__VERSION__ +## Imports from sub-modules -Imports from sub-modules -======================== +### config -config ------- - -.. py:currentmodule:: firebird.driver.config Globals: `driver_config` -core ----- +### core -.. py:currentmodule:: firebird.driver.core Functions: `connect()`, `create_database()`, `connect_server()`, `transaction()` and `tpb()` @@ -36,10 +24,8 @@ Translation dictionaries: Classes: `DistributedTransactionManager`, `Connection`, `Cursor`, `Server` and `TPB` -types ------ +### types -.. py:currentmodule:: firebird.driver.types Exceptions: `Warning`, `Error`, `InterfaceError`, `DatabaseError`, `DataError`, @@ -75,10 +61,7 @@ Helper constants: Helper functions: `get_timezone()` -fbapi ------ +### fbapi -.. py:currentmodule:: firebird.driver.fbapi Functions `load_api()` and `get_api()`. - diff --git a/docs/docs/ref-types.md b/docs/docs/ref-types.md new file mode 100644 index 0000000..065c557 --- /dev/null +++ b/docs/docs/ref-types.md @@ -0,0 +1,291 @@ + +# firebird.driver.types + +## Exceptions + +Next exceptions are required by Python DB API 2.0 + +`Error` is imported from `firebird.base.types`. + +::: firebird.driver.types.Error + +::: firebird.driver.types.InterfaceError + +::: firebird.driver.types.DatabaseError + +::: firebird.driver.types.DataError + +::: firebird.driver.types.OperationalError + +::: firebird.driver.types.IntegrityError + +::: firebird.driver.types.InternalError + +::: firebird.driver.types.ProgrammingError + +::: firebird.driver.types.NotSupportedError + +::: firebird.driver.types.FirebirdWarning + +This is the exception inheritance layout: + +```text +StandardError +|__UserWarning + |__FirebirdWarning +|__Error + |__InterfaceError + |__DatabaseError + |__DataError + |__OperationalError + |__IntegrityError + |__InternalError + |__ProgrammingError + |__NotSupportedError + +``` +## Other constants and types required by Python DB API 2.0 specification + +### Globals + +::: firebird.driver.types.apilevel + +::: firebird.driver.types.threadsafety + +::: firebird.driver.types.paramstyle + +### Helper constants for work with `.Cursor.description` content + +- DESCRIPTION_NAME +- DESCRIPTION_TYPE_CODE +- DESCRIPTION_DISPLAY_SIZE +- DESCRIPTION_INTERNAL_SIZE +- DESCRIPTION_PRECISION +- DESCRIPTION_SCALE +- DESCRIPTION_NULL_OK + +### Types + +::: firebird.driver.types.STRING + +::: firebird.driver.types.BINARY + +::: firebird.driver.types.NUMBER + +::: firebird.driver.types.DATETIME + +::: firebird.driver.types.ROWID + +### Constructors for data types + +::: firebird.driver.types.Date + +::: firebird.driver.types.Time + +::: firebird.driver.types.Timestamp + +::: firebird.driver.types.DateFromTicks + +::: firebird.driver.types.TimeFromTicks + +::: firebird.driver.types.TimestampFromTicks + +::: firebird.driver.types.Binary + +## Types for type hints + +::: firebird.driver.types.DESCRIPTION + +::: firebird.driver.types.CB_OUTPUT_LINE + +::: firebird.driver.types.Transactional + +## Enums + +::: firebird.driver.types.NetProtocol + +::: firebird.driver.types.DirectoryCode + +::: firebird.driver.types.XpbKind + +::: firebird.driver.types.StateResult + +::: firebird.driver.types.PageSize + +::: firebird.driver.types.DBKeyScope + +::: firebird.driver.types.InfoItemType + +::: firebird.driver.types.SrvInfoCode + +::: firebird.driver.types.BlobInfoCode + +::: firebird.driver.types.DbInfoCode + +::: firebird.driver.types.ResultSetInfoCode + +::: firebird.driver.types.Features + +::: firebird.driver.types.ReplicaMode + +::: firebird.driver.types.StmtInfoCode + +::: firebird.driver.types.ReqInfoCode + +::: firebird.driver.types.ReqState + +::: firebird.driver.types.TraInfoCode + +::: firebird.driver.types.TraInfoIsolation + +::: firebird.driver.types.TraInfoReadCommitted + +::: firebird.driver.types.TraInfoAccess + +::: firebird.driver.types.TraAccessMode + +::: firebird.driver.types.TraIsolation + +::: firebird.driver.types.TraReadCommitted + +::: firebird.driver.types.Isolation + +::: firebird.driver.types.TraLockResolution + +::: firebird.driver.types.TableShareMode + +::: firebird.driver.types.TableAccessMode + +::: firebird.driver.types.DefaultAction + +::: firebird.driver.types.StatementType + +::: firebird.driver.types.SQLDataType + +::: firebird.driver.types.DPBItem + +::: firebird.driver.types.TPBItem + +::: firebird.driver.types.SPBItem + +::: firebird.driver.types.BPBItem + +::: firebird.driver.types.BlobType + +::: firebird.driver.types.BlobStorage + +::: firebird.driver.types.ServerAction + +::: firebird.driver.types.SrvDbInfoOption + +::: firebird.driver.types.SrvRepairOption + +::: firebird.driver.types.SrvBackupOption + +::: firebird.driver.types.SrvRestoreOption + +::: firebird.driver.types.SrvNBackupOption + +::: firebird.driver.types.SrvTraceOption + +::: firebird.driver.types.SrvPropertiesOption + +::: firebird.driver.types.SrvValidateOption + +::: firebird.driver.types.SrvUserOption + +::: firebird.driver.types.DbAccessMode + +::: firebird.driver.types.DbSpaceReservation + +::: firebird.driver.types.DbWriteMode + +::: firebird.driver.types.ShutdownMode + +::: firebird.driver.types.OnlineMode + +::: firebird.driver.types.ShutdownMethod + +::: firebird.driver.types.TransactionState + +::: firebird.driver.types.DbProvider + +::: firebird.driver.types.DbClass + +::: firebird.driver.types.Implementation + +::: firebird.driver.types.ImpCPU + +::: firebird.driver.types.ImpOS + +::: firebird.driver.types.ImpCompiler + +::: firebird.driver.types.CancelType + +::: firebird.driver.types.DecfloatRound + +::: firebird.driver.types.DecfloatTraps + +## Flags + +::: firebird.driver.types.StateFlag + +::: firebird.driver.types.PreparePrefetchFlag + +::: firebird.driver.types.StatementFlag + +::: firebird.driver.types.CursorFlag + +::: firebird.driver.types.ConnectionFlag + +::: firebird.driver.types.EncryptionFlag + +::: firebird.driver.types.ServerCapability + +::: firebird.driver.types.SrvRepairFlag + +::: firebird.driver.types.SrvStatFlag + +::: firebird.driver.types.SrvBackupFlag + +::: firebird.driver.types.SrvRestoreFlag + +::: firebird.driver.types.SrvNBackupFlag + +::: firebird.driver.types.SrvPropertiesFlag + +::: firebird.driver.types.ImpFlags + +## Dataclasses + +::: firebird.driver.types.ItemMetadata + options: + members: false + +::: firebird.driver.types.TableAccessStats + options: + members: false + +::: firebird.driver.types.UserInfo + options: + members: false + +::: firebird.driver.types.BCD + options: + members: false + +::: firebird.driver.types.TraceSession + options: + members: false + +::: firebird.driver.types.ImpData + options: + members: false + +::: firebird.driver.types.ImpDataOld + options: + members: false + +## Helper functions + +::: firebird.driver.types.get_timezone diff --git a/docs/docs/usage-guide.md b/docs/docs/usage-guide.md new file mode 100644 index 0000000..5028910 --- /dev/null +++ b/docs/docs/usage-guide.md @@ -0,0 +1,3235 @@ + +# Usage Guide + + +## Driver structure + +Source code is currently divided into next submodules: + +* `types` - Data types used by driver. +* `interfaces` - Interface wrappers for Firebird new API +* `core` - Main driver source code. +* `fbapi` - Python `ctypes` interface to Firebird client library. +* `config` - Driver configuration. +* `hooks` - Drivers hooks. + +All important data, functions, classes and constants are available directly in `firebird.driver` +name space. In normal circumstances is not necessary to import sub-modules directly. However, +you may need them to access some not so frequently needed driver functionality like driver +hooks, or to implement your own callback interfaces. + +!!! important + + `firebird-driver` is designed to support all Firebird versions starting from version 3.0. + Because each Firebird major version adds new functionality, and Firebird OO API could + be extended even in maintenance releases, the driver isolates volatile functionality + into special class hierarchies. + + For example information about database (provided via `~.iAttachment_v3.get_info()` API + call) is isolated into separate `.DatabaseInfoProvider` class hierarchy. + The `.Connection.info` attribute then provides access to instance of appropriate class + - `.DatabaseInfoProvider` or its ancestor - for connected database. + The `.DatabaseInfoProvider` class **always** provides functionality of most recent + Firebird version supported by driver. + + This layout has several important consequences: + + 1. The `.DatabaseInfoProvider` class may change in major driver release if new Firebird + functionality is introduced. This normally represent no problems for client application + as backward compatibility is guaranteed. + 2. You should check the class hierarchy for "evolving" classes when you start using the + driver, and whenever you upgrade to new **major** driver version. If there are versioned + ancestor classes (they always have Firebird version number in their name) for canonical + (top level) ones, you should adjust your application to deal with situations when + instance of ancestor class is provided by driver instead top-level one, to prevent + run-time exceptions caused by access to functionality not provided by currently attached + Firebird server. + + !!! note + + The same apply for low-level API (`~firebird.driver.interfaces`) with difference + that they may change in minor driver releases (because API could be extended in + Firebird maintenance releases). + + !!! info + + `.DatabaseInfoProvider`, `.TransactionInfoProvider`, `.ServerInfoProvider`, + `.ServerDbServices`, `.ServerUserServices` and `.ServerTraceServices`. + + +## Configuration + +The driver uses configuration built on top of [configuration system](https://firebird-base.readthedocs.io/en/latest/config/) +provided by [firebird-base](https://firebird-base.rtfd.io) package. In addition to global settings, the configuration +also includes the definition of connection parameters to Firebird servers and databases. + +The default configuration connects to embedded server using direct/local connection method. +To access remote servers and databases (or local ones through remote protocols), it's +necessary to adjust default configuration, or `register` them in configuration manager. + +You can manipulate the configuration objects directly, or load configuration from files or +strings (in `.ini-style` `configparser` format). + +### The 'driver_config' object + +The global `.driver_config` object holds all configurable driver parameters, and access +configuration parameters for registered Firebird servers and databases. + +In initial state, all parameters have default values and there are no registered servers +and databases. You can set individual parameter values directly, or you can set multiple +parameters (including registered servers and databases) at once by loading them from +configuration string, dict or file(s). + +!!! important + + If you want to use specific Firebird client library, you must set the value of + `.DriverConfig.fb_client_library` configuration option **before** your application + calls any from following functions: `.connect()`, `~firebird.driver.core.create_database()`, + `.connect_server()`, `.load_api()` or `.get_api()`. + +!!! info + + `.DriverConfig` for list of available methods and parameters. + +### Server and database configuration + +Firebird provides ever-increasing list of parameter options for database and server connections. +To keep the Python API clean and manageable, the `firebird-driver` uses server and database +configuration objects instead function parameters to specify values for almost all such options. +Connection functions then provide a name parameter that can refer to particular server / database +or configuration, and few keyword parameters to specify / override selected options. + +!!! important + + The configuration objects does not allow specification of next options: + + - set database encryption callback (for technical reasons) + - set db_key scope (for security reasons) + - disable garbage collection (for security reasons) + - disable database triggers (for security reasons) + - allow overwrite of existing database with newly created database (for security reasons) + + These options could be specified only as keyword arguments in appropriate functions. + +!!! info + + `.ServerConfig` and `.DatabaseConfig` for list of available methods and parameters. + + +## Databases + +Access to the database is made available through `.Connection` objects. Firebird-driver +provides two constructors for these: + +* `.connect` - Returns `.Connection` to database that already exists. +* `~firebird.driver.core.create_database` - Returns `.Connection` to newly created database. + + + +### Using connect() + +This constructor has one positional and several keyword parameters. + +The value of `database` positional parameter must be one of: + +* name of registered database configuration +* database name / alias + +!!! important + This value **cannot** be DSN / fully qualified Firebird connection string! + +Keyword parameters are intended to override selected configuration options, or to specify +options that are not configurable. + +!!! note + + If `database` value is not recognized as name of registered database configuration, + the driver uses `~.DriverConfig.db_defaults` and `~.DriverConfig.server_defaults` + configuration objects. + +A simple database connection is typically established with code such as this: + +```python +from firebird.driver import connect + +# Attach to 'employee' database/alias using embedded server connection +con = connect('employee', user='sysdba', password='masterkey') + +# Attach to 'employee' database/alias using local server connection +from firebird.driver import driver_config +driver_config.server_defaults.host.value = 'localhost' +con = connect('employee', user='sysdba', password='masterkey') + +# Set 'user' and 'password' via configuration +driver_config.server_defaults.user.value = 'SYSDBA' +driver_config.server_defaults.password.value = 'masterkey' +con = connect('employee') + +``` + +However, it's recommended to use specific configuration for servers and databases. +It's possible to register servers and databases directly in code like this: + +```python +from firebird.driver import connect, driver_config + +# Register Firebird server +srv_cfg = """[local] +host = localhost +user = SYSDBA +password = masterkey +""" +driver_config.register_server('local', srv_cfg) + +# Register database +db_cfg = """[employee] +server = local +database = employee.fdb +protocol = inet +charset = utf8 +""" +driver_config.register_database('employee', db_cfg) + +# Attach to 'employee' database +con = connect('employee') + +``` + +But more convenient approach is using single configuration file: + +```text +# file: myapp.cfg + +[firebird.driver] +servers = local +databases = employee + +[local] +host = localhost +user = SYSDBA +password = masterkey + +[employee] +server = local +database = employee.fdb +protocol = inet +charset = utf8 + +``` + +```python +from firebird.driver import connect, driver_config + +driver_config.read('myapp.cfg') + +# Attach to 'employee' database +con = connect('employee') + +``` + +!!! info + `.connect()` for details. + + +### Using create_database() + +This constructor returns connection to newly created database. It works in the same way +as `.connect()`, but utilizes additional database configuration options. + +It's possible to specify these options in code like this: + +```python +from firebird.driver import connect, driver_config + +# Register Firebird server +srv_cfg = """[local] +host = localhost +user = SYSDBA +password = masterkey +""" +driver_config.register_server('local', srv_cfg) + +# Register database +db_cfg = """[mydb] +server = local +database = mydb.fdb +protocol = inet +charset = utf8 +# create options +page_size = 16384 +db_charset = utf8 +sweep_interval = 80000 +reserve_space = no +""" +driver_config.register_database('mydb', db_cfg) + +# create 'mydb' database +con = create_database('mydb') + +``` + +But more convenient approach is using single configuration file: + +```text +# file: myapp.cfg + +[firebird.driver] +servers = local +databases = mydb + +[local] +host = localhost +user = SYSDBA +password = masterkey + +[mydb] +server = local +database = mydb.fdb +protocol = inet +charset = utf8 +# create options +page_size = 16384 +db_charset = utf8 +sweep_interval = 80000 +reserve_space = no + +``` + +```python +from firebird.driver import create_database, driver_config + +driver_config.read('myapp.cfg') + +# create 'mydb' database +con = create_database('mydb') + +``` + +!!! info + `~firebird.driver.core.create_database()` for details. + + +### Deleting databases + +The Firebird engine also supports dropping (deleting) databases dynamically, +but dropping is a more complicated operation than creating, for several reasons: +an existing database may be in use by users other than the one who requests +the deletion, it may have supporting objects such as temporary sort files, and +it may even have dependent shadow databases. Although the database engine +recognizes a `DROP DATABASE` SQL statement, support for that statement is limited +to the `isql` command-line administration utility. However, the engine supports +the deletion of databases via an API call, which `firebird-driver` exposes as +`~.Connection.drop_database` method in `.Connection` class. So, to drop a database +you need to connect to it first. + +**Example:** + +```python +from firebird.driver import connect, driver_config + +driver_config.read('myapp.cfg') + +# Attach to 'myapp' database +con = connect('myapp') +con.drop_database() + +``` + +!!! info + `.Connection.drop_database()` for details. + + +### Connection object + +`.Connection` object represents a direct link to database, and works as +gateway for next operations with it: + +* [Executing SQL Statements](usage-guide.md#executing-sql-statements): methods `~.Connection.execute_immediate()` and `~.Connection.cursor()`. +* [Dropping database](usage-guide.md#deleting-databases): method `~.Connection.drop_database()`. +* [Transanction management](usage-guide.md#transanction-management): methods `~.Connection.begin()`, `~.Connection.commit()`, + `~.Connection.rollback()`, `~.Connection.savepoint()`, `~.Connection.transaction_manager()`, + `~.Connection.is_active()`, and attributes `~.Connection.main_transaction`, + `~.Connection.query_transaction`, `~.Connection.transactions` and `~.Connection.default_tpb`. +* Work with [Database Events](usage-guide.md#database-events): method `~.Connection.event_collector`. +* [Getting information about connection](usage-guide.md#getting-information-about-connection): methods `~.Connection.is_closed()` and + `~.Connection.ping()` and attributes `~.Connection.dsn`, `~.Connection.charset` + and `~.Connection.sql_dialect`. +* [Getting information about database](usage-guide.md#getting-information-about-database): attribute `~.Connection.info`. +* [Closing the connection](usage-guide.md#closing-the-connection): method `~.Connection.close()` + + +### Closing the connection + +There are many local and server resources used by firebird-driver that must be properly +managed, and disposed when they are no longer necessary. All objects that require proper +finalization provide `close()` method that must be called when object is no longer needed. +The `.Connection` (and `.Server`) objects are the most important ones, as other most frequently +used objects like cursors, prepared statements and transactions are typically associated with +connections. + +You may call the `close()` method directly, or use the with statement +and context manager support provided by all these objects. + +**Example:** + +```python +from firebird.driver import connect, driver_config + +driver_config.read('myapp.cfg') + +with connect('employee') as con: + cur = con.cursor() + cur.execute('select 1 from rdb$database') + print(cur.fetchone()[0]) + + +``` + +!!! note + + Objects that require proper finalization are: `.Connection`, `.TransactionManager` + and `.DistributedTransactionManager`, `.Statement`, `.BlobReader`, `.Cursor` and `.Server`. + + Although only `.Connection` and `.Server` objects must be closed directly because + all other objects are associated with them and thus closed when connection is + closed, it's **recommended** to directly close any resource object obtained by + your code when it's no longer needed (either directly by calling `close()` or using + `with` statement). + +!!! important + + All managed objects have `~object.__del__` method, which ensures that the object in + the active state is properly closed before it is destroyed by the Python memory manager. + However, **the close operation may fail** as the state of your application could be arbitrary + and the sequence in which objects are disposed by memory manager is not deterministic. + + The `~object.__del__` methods should be thus considered as safe guard of last resort + that your code should not rely upon. To indicate that your code is not managing + resources properly, the `ResourceWarning` is raises when active object is disposed + by memory manager. + + !!! note + + Such warnings may not reach your attention if warnings are disabled or filtered + on your system. You should always develop and test your applications with enabled + delivery of resource warnings. + +!!! info + `.Connection.close()` for details. + + +### Getting information about connection + +Only (most useful) part of information associated with `.Connection` object is directly +available: + +* It's possible to check whether Connection object is closed or not with + `~.Connection.is_closed()` method. +* It's possible to check whether connection to the Firebird server is not broken with + `~.Connection.ping()` method. +* The DSN (fully qualified Firebird database connection string) is surfaced as `~.Connection.dsn` + read-only property. +* The character set used by Connection is surfaced as `~.Connection.charset` read-only property. +* The SQL dialect used by Connection is surfaced as `~.Connection.sql_dialect` read-only property. + +!!! tip + + Additional connection-specific information is currently held as `bytes` in protected + `Connection._dpb` attribute that could be processed using `~firebird.driver.core.DPB` object. + + +### Getting information about database + +!!! important + + Because the scope and type of database information depends on the version of the Firebird + server and database ODS, this information is made available through a separate class + `.DatabaseInfoProvider`. The `.Connection.info` property provides access to + instance of `.DatabaseInfoProvider` or it's **ancestor** class according to ODS of attached + database and Firebird version. + +Although you may query the information directly from server using +`~firebird.driver.core.DatabaseInfoProvider3.get_info()` method (that wraps the Firebird +`.iAttachment.getInfo()` API call), the `.DatabaseInfoProvider` object +provides more convenient methods and properties for obtaining specific information directly. + +!!! note + + Some information provided by `.DatabaseInfoProvider` properties + (like `~.DatabaseInfoProvider3.cache_hit_ratio`) could not be obtained via + `get_info()` method. + +**Example:** + +```python +from firebird.driver import connect + +with connect('employee', user='SYSDBA', password='masterkey') as con: + print(f"Database character set: {con.info.charset}") + print(f"Page size (in bytes): {con.info.page_size}") + print(f"Attachment ID: {con.info.id}") + print(f"SQL dialect used by connected database: {con.info.sql_dialect}") + print(f"Database name (filename or alias): {con.info.name}") + print(f"Database site name: {con.info.site}") + print(f"Implementation (old format): {con.info.implementation!s}") + print(f"Database Provider: {con.info.provider!s}") + print(f"Database Class: {con.info.db_class!s}") + print(f"Date when database was created: {con.info.creation_date}") + print(f"Size of page cache used by connection: {con.info.page_cache_size}") + print(f"Number of pages allocated for database: {con.info.pages_allocated}") + print(f"Number of database pages in active use: {con.info.pages_used}") + print(f"Number of free allocated pages in database: {con.info.pages_free}") + print(f"Sweep interval: {con.info.sweep_interval}") + print(f"Data page space usage (USE_FULL or RESERVE): {con.info.space_reservation!s}") + print(f"Database write mode (SYNC or ASYNC): {con.info.write_mode!s}") + print(f"Database access mode (READ_ONLY or READ_WRITE): {con.info.access_mode!s}") + print(f"Current I/O statistics - Reads from disk to page cache: {con.info.reads}") + print(f"Current I/O statistics - Fetches from page cache: {con.info.fetches}") + print(f"Cache hit ratio = 1 - (reads / fetches): {con.info.cache_hit_ratio}") + print(f"Current I/O statistics - Writes from page cache to disk: {con.info.writes}") + print(f"Current I/O statistics - Writes to page in cache: {con.info.marks}") + print(f"Total amount of memory curretly used by database engine: {con.info.current_memory}") + print(f"Max. total amount of memory so far used by database engine: {con.info.max_memory}") + print(f"ID of Oldest Interesting Transaction: {con.info.oit}") + print(f"ID of Oldest Active Transaction: {con.info.oat}") + print(f"ID of Oldest Snapshot Transaction: {con.info.ost}") + print(f"ID for next transaction: {con.info.next_transaction}") + +``` + +**Sample output**: + +```text +Database character set: NONE +Page size (in bytes): 8192 +Attachment ID: 378 +SQL dialect used by connected database: 3 +Database name (filename or alias): /opt/firebird/examples/empbuild/employee.fdb +Database site name: NewAmarisk +Implementation (old format): Implementation.RDB_VMS +Database Provider: DbProvider.FIREBIRD +Database Class: DbClass.SERVER_ACCESS +Date when database was created: 2020-05-13 10:13:57.005010 +Size of page cache used by connection: 2048 +Number of pages allocated for database: 346 +Number of database pages in active use: 311 +Number of free allocated pages in database: 35 +Sweep interval: 20000 +Data page space usage (USE_FULL or RESERVE): DbSpaceReservation.RESERVE +Database write mode (SYNC or ASYNC): DbWriteMode.SYNC +Database access mode (READ_ONLY or READ_WRITE): DbAccessMode.READ_WRITE +Current I/O statistics - Reads from disk to page cache: 87 +Current I/O statistics - Fetches from page cache: 1525 +Cache hit ratio = 1 - (reads / fetches): 0.9429508196721311 +Current I/O statistics - Writes from page cache to disk: 2 +Current I/O statistics - Writes to page in cache: 5 +Total amount of memory curretly used by database engine: 21925248 +Max. total amount of memory so far used by database engine: 22033760 +ID of Oldest Interesting Transaction: 307 +ID of Oldest Active Transaction: 308 +ID of Oldest Snapshot Transaction: 308 +ID for next transaction: 308 + +``` + +!!! info + `.DatabaseInfoProvider` for details. + +#### Getting information about Firebird version + +Because functionality and some features depends on actual Firebird version, it could be +important for driver users to check it. This (otherwise) simple task could be confusing +for new Firebird users, because Firebird uses two different version lineages. This abomination +was introduced to Firebird thanks to its InterBase legacy (Firebird 1.0 is a fork of InterBase +6.0), as applications designed to work with InterBase can often work with Firebird without +problems (and vice versa). + +`.DatabaseInfoProvider` provides these version strings as two properties: + +* `~.DatabaseInfoProvider.server_version` - Legacy InterBase-friendly version string. +* `~.DatabaseInfoProvider.firebird_version` - Firebird’s own version string. + +However, this version string contains more information than version number. For example for +Linux Firebird 4.0.0 it’s ‘LI-T4.0.0.1963 Firebird 4.0 Beta 2’. So `.DatabaseInfoProvider` +provides two more properties for your convenience: + +* `~.DatabaseInfoProvider.version` - Only Firebird version number. It’s a string with + format: major.minor.subrelease.build +* `~.DatabaseInfoProvider.engine_version` - Engine (major.minor) version as (float) number. + + +**Example:** + +```python +from firebird.driver import connect + +with connect('employee', user='SYSDBA', password='masterkey') as con: + print(f"server_version: '{con.info.server_version}'") + print(f"firebird_version: '{con.info.firebird_version}'") + print(f"version: '{con.info.version}'") + print(f"engine_version: {con.info.engine_version}") + +``` + +**Sample output**: + +```text +server_version: 'LI-T6.3.0.1963 Firebird 4.0 Beta 2' +firebird_version: 'LI-T4.0.0.1963 Firebird 4.0 Beta 2' +version: '4.0.0.1963' +engine_version: 4.0 + +``` +#### Database On-Disk Structure + +Particular Firebird features may also depend on specific support in database +(for example number and structure of monitoring tables). These required structures are +present automatically when database is created by particular engine verison that needs +them, but Firebird engine may work with databases created by older versions and thus with +older structure, so it could be necessary to consult also On-Disk Structure (ODS for short) +version. `.DatabaseInfoProvider` provides this number as `~.DatabaseInfoProvider.ods` (float) +property. + +**Example:** + +```python +from firebird.driver import connect + +with connect('employee', user='SYSDBA', password='masterkey') as con: + print(f"ods: {con.info.ods}") + print(f"ods_version: {con.info.ods_version}") + print(f"ods_minor_version: {con.info.ods_minor_version}") + +``` + +**Sample output**: + +```text +ods: 13.0 +ods_version: 13 +ods_minor_version: 0 + + + +``` + +## Executing SQL Statements + +Firebird-driver implements two ways for execution of SQL commands against connected database: + +* `~.Connection.execute_immediate` - for execution of SQL commands that don't return any result. +* `.Cursor` objects that offer rich interface for execution of SQL commands and fetching their results. + + + +### Cursor object + +Because `.Cursor` objects always operate in context of single `.Connection` (and `.TransactionManager`), +`.Cursor` instances are not created directly, but by constructor method. Python DB API 2.0 assumes +that if database engine supports transactions, it supports only one transaction per connection, +hence it defines constructor method `~.Connection.cursor` (and other transaction-related methods) +as part of `.Connection` interface. However, Firebird supports multiple independent transactions +per connection. To conform to Python DB API, firebird-driver uses concept of internal +`~.Connection.main_transaction` and secondary `~.Connection.transactions`. Cursor constructor is +primarily defined by `.TransactionManager`, and Cursor constructor on `.Connection` is therefore +a shortcut for `main_transaction.cursor()`. + +`.Cursor` objects are used for next operations: + +* Execution of SQL Statemets: methods `~.Cursor.execute()`, `~.Cursor.executemany()`, `~.Cursor.open()` + and `~.Cursor.callproc()`. +* Creating `.Statement` objects for efficient repeated execution of SQL statements, and to obtain + additional information about SQL statements (like execution `~.Statement.plan`): method `~.Cursor.prepare()`. +* [Fetching results](usage-guide.md#fetching-data-from-server): methods `~.Cursor.fetchone()`, `~.Cursor.fetchmany()`, + `~.Cursor.fetchall()`, `~.Cursor.fetch_next()`, `~.Cursor.fetch_prior()`, `~.Cursor.fetch_first()`, + `~.Cursor.fetch_last()`, `~.Cursor.fetch_absolute()` and `~.Cursor.fetch_relative()`. + + +### SQL Execution Basics + +There are five methods how to execute SQL commands: + +1. `.Connection.execute_immediate()` or `.TransactionManager.execute_immediate()` for SQL commands + that don't return any result, and are not executed frequently. This method also **doesn't** + support either [parameterized statements](usage-guide.md#parameterized-statements) or + [prepared statements](usage-guide.md#prepared-statements). + + !!! tip + + This method is efficient for `administrative` and [DDL](http://en.wikipedia.org/wiki/Data_Definition_Language) SQL commands, like `DROP`, `CREATE` + or `ALTER` commands, `SET STATISTICS` etc. + +2. `.Cursor.execute()` for SQL commands that return result sets, i.e. sequence of `rows` of the same + structure, and sequence has unknown number of `rows` (including zero). Each row of the sequence + can be read only once, and is returned in the order it is read from the server. + + !!! tip + + This method is preferred for all `SELECT` and other [DML](http://en.wikipedia.org/wiki/Data_Manipulation_Language) statements, or any statement that + is executed frequently, either `as is` or in `parameterized` form. + +3. `.Cursor.executemany()` for execution of single parameterized SQL command with various set + of parameters. + + !!! important + + Because `executemany()` is basically a simple loop that calls `execute()` with different + parameters, it's possible to execute any statement acceptable by `execute()`. However, + it's possible to access the result set **only** from last executed command, so this method + should not be used for SQL commands that return results. + +4. `.Cursor.open()` for SQL command that return result sets, i.e. sequence of `rows` of the same + structure, and sequence has unknown number of `rows` (including zero). Instead of just fetching + rows sequentially in a forward direction like `execute()`, this method allows flexible navigation + through an open cursor set both backwards and forwards. Rows next to, prior to and relative to + the current cursor row can be targeted. + + !!! info + [Scrollable cursors](usage-guide.md#scrollable-cursors) for details. + +5. `.Cursor.callproc()` for execution of `Stored procedures` that always return exactly one set + of values. + + !!! note + + This method of SP invocation is equivalent to `"EXECUTE PROCEDURE ..."` SQL statement. + + +### Fetching data from server + +Result of SQL statement execution consists from sequence of zero to unknown number of `rows`, +where each `row` is a set of exactly the same number of values. `.Cursor` object offer number +of different methods for fetching these `rows`, that should satisfy all your specific needs: + +* `~.Cursor.fetchone()` - Returns the next row of a query result set, or `None` when no more data + is available. + + !!! tip + + Cursor supports the [iterator protocol](https://docs.python.org/3/library/stdtypes.html#iterator-types), yielding tuples of values + like `~.Cursor.fetchone()`. + +* `~.Cursor.fetchmany()` - Returns the next set of rows of a query result, returning a sequence + of sequences (e.g. a list of tuples). An empty sequence is returned when no more rows are available. + + The number of rows to fetch per call is specified by the parameter. If it is not given, the + cursor’s `~.Cursor.arraysize` determines the number of rows to be fetched. The method does try + to fetch as many rows as indicated by the size parameter. If this is not possible due to + the specified number of rows not being available, fewer rows may be returned. + + !!! note + + The default value of `~.Cursor.arraysize` is `1`, so without paremeter it's equivalent to + `~.Cursor.fetchone()`, but returns list of `rows`, instead actual `row` directly. + +* `~.Cursor.fetchall()` - Returns all (remaining) rows of a query result as list of tuples, + where each tuple is one row of returned values. + + !!! tip + + This method can potentially return huge amount of data, that may exhaust available memory. + If you need just `iteration` over potentially big result set, use loops with `~.Cursor.fetchone()` + or Cursor's built-in support for [iterator protocol](https://docs.python.org/3/library/stdtypes.html#iterator-types) instead this method. + +* Call to `~.Cursor.execute()` returns `self` (Cursor instance) that itself supports the + [iterator protocol](https://docs.python.org/3/library/stdtypes.html#iterator-types), yielding tuples of values like `~.Cursor.fetchone()`. + +!!! important + + Firebird-driver makes absolutely no guarantees about the `row` return value of the + `fetch*()` methods except that it is a sequence indexed by field position. Therefore, client + programmers should not rely on the return value being an instance of a particular class or type. + +**Examples:** + +```python +from firebird.driver import connect + +with connect('employee', user='SYSDBA', password='masterkey') as con: + cur = con.cursor() + SELECT = "select country, currency from country" + + # 1. Using built-in support for iteration protocol to iterate over the rows available + # from the cursor, unpacking the resulting sequences to yield their elements (country, currency): + cur.execute(SELECT) + for (country, currency) in cur: + print(f"{country} uses {currency} as currency.") + # or alternatively you can take an advantage of cur.execute() returning self. + for (country, currency) in cur.execute(SELECT): + print(f"{country} uses {currency} as currency.") + + # 2. Equivalently using fetchall(): + # This is potentially dangerous if result set is huge, as the whole result set is + # first materialized as list and then used for iteration. + cur.execute(SELECT) + for row in cur.fetchall(): + print(f"{row[0]} uses {row[1]} as currency.") + +``` + +!!! important + + Method `.Cursor.executemany()` is not intended for operations that return results, + so it does **NOT** returns `self` like `.Cursor.execute()`, and you can't use calls + to this method as iterator. + + + + +### Scrollable cursors + +SQL statements executed by `.Cursor.open()` have scrollable result set that could be +navigated using next methods: + +* `~.Cursor.fetch_next()` - Moves the cursor's current position to the next row and + returns it. Returns `None` if the cursor is empty or already positioned at the last row. + +* `~.Cursor.fetch_prior()` - Moves the cursor's current position to the prior row and + returns it. Returns `None` if the cursor is empty or already positioned at the first row. + +* `~.Cursor.fetch_first()` - Moves the cursor's current position to the first row and + returns it. Returns `None` if the cursor is empty. + +* `~.Cursor.fetch_last()` - Moves the cursor's current position to the last row and + returns it. Returns `None` if the cursor is empty. + +* `~.Cursor.fetch_absolute()` - Moves the cursor's current position to the specified + and returns the located row. Returns `None` if is beyond the + cursor's boundaries. + +* `~.Cursor.fetch_relative()` - Moves the cursor's current position backward or forward + by the specified and returns the located row. Returns `None` if the calculated + position is beyond the cursor's boundaries. + +!!! important + + Please note that scrollable cursors: + + a) are not supported by all versions of Firebird server. + + b) are internally materialized as a temporary record set, thus consuming + memory/disk resources, so this feature should be used only when really necessary. + +**Example:** + +```python +from firebird.driver import connect + +def print_row(row): + if row: + print(f"{row[0]}, {row[1]}, {row[2]}") + else: + print('NO DATA') + +with connect('employee', user='SYSDBA', password='masterkey') as con: + cur = con.cursor() + cur.open('select row_number() over (order by country), country, currency from country order by country') + + # You can iterate over scrollable cursors + for row in cur: + print_row(row) + + print('-' * 10) + # or fetch particular rows directly + print_row(cur.fetch_first()) + print_row(cur.fetch_last()) + print_row(cur.fetch_absolute(10)) + print_row(cur.fetch_next()) + print_row(cur.fetch_prior()) + print_row(cur.fetch_relative(-5)) + print_row(cur.fetch_relative(10)) + + print('-' * 10) + + cur.fetch_last() + print_row(cur.fetch_next()) + +``` + +**Sample output**: + +```text +1, Australia, ADollar +2, Austria, Euro +3, Belgium, Euro +4, Canada, CdnDlr +5, England, Pound +6, Fiji, FDollar +7, France, Euro +8, Germany, Euro +9, Hong Kong, HKDollar +10, Italy, Euro +11, Japan, Yen +12, Netherlands, Euro +13, Romania, RLeu +14, Russia, Ruble +15, Switzerland, SFranc +16, USA, Dollar +---------- +1, Australia, ADollar +16, USA, Dollar +10, Italy, Euro +11, Japan, Yen +10, Italy, Euro +5, England, Pound +15, Switzerland, SFranc +---------- +NO DATA + +``` + + + +### Parameterized statements + +When SQL command you want to execute contains data `values`, you can either: + +* Embed them `directly` or via `string formatting` into command string, e.g.: + + ```python + cur.execute("insert into the_table (a,b,c) values ('aardvark', 1, 0.1)") + # or + cur.execute("select * from the_table where col == 'aardvark'") + # or + cur.execute("insert into the_table (a,b,c) values ('%s', %i, %f)" % ('aardvark',1,0.1)) + # or + cur.execute(f"select * from the_table where col == '{value}'") + + ``` + +* Use parameter marker (`?`) in command string in the slots where values are expected, + then supply those values as Python list or tuple: + + ```python + cur.execute("insert into the_table (a,b,c) values (?,?,?)", ('aardvark', 1, 0.1)) + # or + cur.execute("select * from the_table where col == ?",('aardvark',)) + + ``` + +While both methods have the same results, the second one (called `parametrized`) has several +important advantages: + +* You don't need to handle conversions from Python data types to strings. +* Firebird-driver will handle all data type conversions (if necessary) from Python data types + to Firebird ones, including `None/NULL` conversion and conversion from `str` to `bytes` + in encoding expected by server. +* You may pass BLOB values as open `file-like` objects, and firebird-driver will handle the + transfer of BLOB value. + +Parametrized statemets also have some limitations. Currently: + +* `DATE`, `TIME` and `DATETIME` values must be relevant `datetime` objects. +* `NUMERIC` and `DECIMAL` values must be `decimal` objects. + + + + +### Prepared Statements + +Execution of any SQL statement has three phases: + +* *Preparation*: command is analyzed, validated, execution plan is determined + by optimizer and all necessary data structures (for example for input and output + parameters) are initialized. +* *Execution*: input parameters (if any) are passed to server and previously + prepared statement is actually executed by database engine. +* *Fetching*: result of execution and data (if any) are transferred from server + to client, and allocated resources are then released (by closing the statement). + +The preparation phase consumes some amount of server resources (memory and CPU). +Although preparation and release of resources typically takes only small amount +of CPU time, it builds up as number of executed statements grows. Firebird (like +most database engines) allows to spare this time for subsequent execution if +particular statement should be executed repeatedly - by reusing once prepared +statement for repeated execution. This may save significant amount of server +processing time, and result in better overall performance. + +Firebird-driver builds on this by encapsulating the Firebird SQL statement data +and related code into separate `.Statement` class, and implementing the `.Cursor` +class around it. The Cursor uses either an internally managed `.Statement` instance +to execute SQL commands provided as `string`, or uses `.Statement` instance +provided by your code as SQL command. + +To get the (prepared) `.Statement` instance for later (repeated) execution, use +`~.Cursor.prepare()` method. You can then pass this instance to `~.Cursor.execute()`, +`~.Cursor.executemany()` or `~.Cursor.open()` instead `command string`. + +`.Statement` instances are bound to `.Connection` instance, and can't be used +with any other `.Connection`. Beside repeated execution they are also useful +to get information about statement (like its execution `~.Statement.plan` or +`~.Statement.type`) before its execution. + +!!! note + + The internally managed `.Statement` instance is released when `.Cursor` is closed, + or before any new statement is executed. It means that if your code executes + the same SQL command (passed as string) repeatedly without closing the cursor + between calls, the same `.Statement` instance is (re)used. + +!!! important + + Implementation of Cursor in firebird-driver somewhat violates the Python DB API 2.0, + which requires that cursor will be unusable after call to `~.Cursor.close()`; and + an Error (or subclass) exception should be raised if any operation is attempted with + the cursor. In firebird-driver, the `.Cursor.close()` call only releases resources + associated with executed statement like the result set, and you can't fetch data or + query information about the SQL statement. However, you can use the cursor instance + to execute new SQL commands. + + !!! warning + + If you'll take advantage of this anomaly, your code would be less portable to other + Python DB API 2.0 compliant drivers. + +**Example:** + +```python +insertStatement = cur.prepare("insert into the_table (a,b,c) values (?,?,?)") + +inputRows = [ + ('aardvark', 1, 0.1), + ('zymurgy', 2147483647, 99999.999), + ('foobar', 2000, 9.9) + ] + +for row in inputRows: + cur.execute(insertStatement,row) +# +# or you can use executemany +# +cur.executemany(insertStatement, inputRows) + + +``` + +!!! info + `.Statement` for details. + + +### Named Cursors + +To allow the Python programmer to perform scrolling **UPDATE** or **DELETE** via the +**“SELECT ... FOR UPDATE”** syntax, the firebird-driver provides the read-only property +`.Cursor.name` and method `.Cursor.set_cursor_name()`. + +**Example Program:** + +```python +from firebird.driver import connect + +with connect('employee', user='sysdba', password='masterkey') as con: + curScroll = con.cursor() + curUpdate = con.cursor() + + curScroll.execute("select city from customer for update") + curScroll.set_cursor_name('city_scroller') + update = "update customer set city=? where current of " + curScroll.name + + for (city,) in curScroll: + city = ... # make some changes to city + curUpdate.execute( update, (city,) ) + + con.commit() + +``` + + +### Working with stored procedures + +Firebird stored procedures can have input parameters and/or output parameters. +Some databases support input/output parameters, where the same parameter is used +for both input and output; Firebird does not support this. + +It is important to distinguish between procedures that **return a result set** and +procedures that **populate and return their output parameters** exactly once. Conceptually, +the latter “return their output parameters” like a Python function, whereas the former +“yield result rows” like a Python generator. + +Firebird’s **server-side** procedural SQL syntax makes no such distinction, but client-side +SQL code (and C API code) must. A result set is retrieved from a stored procedure by +**SELECT'ing from the procedure, whereas output parameters are retrieved with an +'EXECUTE PROCEDURE' statement**. + +To **retrieve a result set** from a stored procedure with firebird-driver, use code +such as this: + +```python +cur.execute("select output1, output2 from the_proc(?, ?)", (input1, input2)) + +# Ordinary fetch code here, such as: +for row in cur: + ... # process row + +con.commit() # If the procedure had any side effects, commit them. + +``` + +To **execute** a stored procedure and **access its output parameters**, you can +choose from two options: + +1. Method `.Cursor.callproc()` that **conforms to Python DB API 2.0**. This method + does not returns the output parameters directly, and you must call `.Cursor.fetchone()` + **exactly once** to retrieve them. + +2. Method `.Cursor.call_procedure()` that returns output parameters directly + (or `None` if procedure does not have output parameters). + +**Examples:** + +```python +# Python DB API 2.0 compliant method: +cur.callproc("the_proc", (input1, input2)) +# If there are output parameters, retrieve them as though they were the +# first row of a result set... +outputParams = cur.fetchone() + +# alternative method: +outputParams = cur.call_procedure("the_proc", (input1, input2)) + +con.commit() # If the procedure had any side effects, commit them. + + +``` + + +## Data handling and conversions + + +### Implicit Conversion of Input Parameters from Strings + +The Firebird database engine treats most SQL data types in a weakly typed fashion: +the engine may attempt to convert the raw value to a different type, as appropriate +for the current context. For instance, the SQL expressions `123` (integer) and `‘123’` +(string) are treated equivalently when the value is to be inserted into an `integer` +field; the same applies when `‘123’` and `123` are to be inserted into a `varchar` field. + +This weak typing model is quite unlike Python’s dynamic yet strong typing. Although +weak typing is regarded with suspicion by most experienced Python programmers, the +database engine is in certain situations so aggressive about its typing model that +firebird-driver must compromise in order to remain an elegant means of programming +the database engine. + +An example is the handling of “magic values” for date and time fields. The database +engine interprets certain string values such as `‘yesterday’` and `‘now’` as having +special meaning in a date/time context. If firebird-driver did not accept strings as +the values of parameters destined for storage in date/time fields, the resulting code +would be awkward. Consider the difference between the two Python snippets below, which +insert a row containing an integer and a timestamp into a table defined with the following +DDL statement: + +```sql +create table test_table (i integer, t timestamp) + +``` + +```python +i = 1 +t = 'now' +sqlWithMagicValues = f"insert into test_table (i, t) values (?, '{t}')" +cur.execute(sqlWithMagicValues, (i,)) + +``` + +```python +i = 1 +t = 'now' +cur.execute("insert into test_table (i, t) values (?, ?)", (i, t)) + +``` + +If firebird-driver did not support weak parameter typing, string parameters that +the database engine is to interpret as “magic values” would have to be rolled into +the SQL statement in a separate operation from the binding of the rest of the parameters, +as in the first Python snippet above. Implicit conversion of parameter values from +strings allows the consistency evident in the second snippet, which is both more +readable and more general. + +!!! note + + It should be noted that firebird-driver does not perform the conversion from string + itself. Instead, it passes that responsibility to the database engine by changing + the parameter metadata structure dynamically at the last moment, then restoring + the original state of the metadata structure after the database engine has performed + the conversion. + +A secondary benefit is that when one uses firebird-driver to import large amounts +of data from flat files into the database, the incoming values need not necessarily +be converted to their proper Python types before being passed to the database engine. +Eliminating this intermediate step may accelerate the import process considerably, +although other factors such as the chosen connection protocol and the deactivation +of indexes during the import are more consequential. For bulk import tasks, the +database engine’s external tables also deserve consideration. External tables can +be used to suck semi-structured data from flat files directly into the relational +database without the intervention of an ad hoc conversion program. + + +### Automatic conversion from/to Unicode + +In Firebird, every `CHAR`, `VARCHAR` or textual `BLOB` field can (or, better: must) +have a `character set` assigned. While it's possible to define single character set +for whole database, it's also possible to define different character set for each +textual field. This information is used to correctly store the bytes that make up +the character string, and together with collation information (that defines the sort +ordering and uppercase conversions for a string) is vital for correct data manipulation, +including automatic transliteration between character sets when necessary. + +!!! important + + Because data also flow between server and client application, it's vital that client + will send data encoded only in character set(s) that server expects. While it's + possible to leave this responsibility completely on client application, it's better + when client and server settle on single character set they would use for communication, + especially when database operates with multiple character sets, or uses character set + that is not `native` for client application. + + Character set for communication is specified using `~.DatabaseConfig.charset` + configuration option, or parameter in `.connect()` or `~firebird.driver.core.create_database()` call. + + When `connection charset` is defined, all textual data returned from server are encoded + in this charset, and client application must ensure that all textual data sent to server + are encoded only in this charset as well. + +Firebird-driver helps with client side of this character set bargain by automatically +converting Python `str` values into `bytes` encoded in connection character set, +and vice versa. However, developers are still responsible that `bytes` strings +passed to server are in correct encoding (because firebird-driver makes no assumption +about encoding of `bytes` strings, so it can't recode them to connection charset). + +!!! important + + In case that `connection charset` is NOT defined at all, or `NONE` charset is specified, + firebird-driver uses `locale.getpreferredencoding` to determine encoding for conversions + from/to `unicode`. + +!!! important + + There is one exception to automatic conversion: when character set OCTETS is defined + for data column. Values assigned to OCTETS columns are always passed `as is`, because + they're basically binary streams. This has specific implications. Python 3 native + strings are `unicode`, and you would probably want to use `bytes` type instead. However, + firebird-driver in this case doesn't check the value type at all, so you'll not be + warned if you'll make a mistake and pass `str` to OCTETS column (unless you'll pass + more bytes than column may hold, or you intend to store unicode that way). + +Conversion is fully automatic in both directions for all textual data, i.e. including +for string values returned by Firebird Service and `info` calls etc. When `connection +charset` is not specified, firebird-driver uses `locale.getpreferredencoding` to +determine encoding for conversions from/to `unicode`. + +!!! tip + + Except for legacy databases that doesn't have `character set` defined, **always** + define character set for your databases and specify `connection charset`. It will + make your life much easier. + + + + +### Working with TIME/TIMESTAMP WITH TIMEZONE + +Firebird 4 introduced support for TIME and TIMESTAMP WITH TIMEZONE. The driver supports these +types with timezone-aware `datetime.datetime` and `datetime.time` objects. However, this +support has some specific limitations: + +1. The driver uses `python-dateutil` package to handle timezone information. Due to specific + requirements it's not possible to use standard `zoneinfo` package available in Python since + version 3.9, neither any other `datetime.tzinfo` implementation. +2. All timezone-aware `datetime.datetime` and `datetime.time` objects passed to the driver + must use `datetime.tzinfo` created with `.get_timezone()` utility function. + +**Examples:** + +```python +from firebird.driver import get_timezone + +ts_region = datetime.datetime(2020, 12, 31, 23, 55, 35, 123400, get_timezone('Europe/Prague')) +ts_offset = datetime.datetime(2020, 12, 31, 23, 55, 35, 123400, get_timezone('+02:00')) + +``` + +### Working with BLOBs + +Firebird-driver uses two types of BLOB values: + +* **Materialized** BLOB values are Python `str` or `bytes` values. This is the **default** type. +* **Streamed** BLOB values are `file-like` objects. + +Materialized BLOBs are easy to work with, but are not suitable for: + +* **deferred loading** of BLOBs. They're called `materialized` because they're always + fetched from server as part of row fetch. Fetching BLOB value means separate API calls + (and network roundtrips), which may slow down you application considerably. +* **large values**, as they are always stored in memory in full size. + +These drawbacks are addressed by `stream` BLOBs. Using BLOBs in `stream` mode is easy: + +* For **input** values, simply use [parameterized statement](usage-guide.md#parameterized-statements) + and pass any `file-like` object in place of BLOB parameter. The `file-like` object must + implement only the `~file.read` method, as no other method is used. +* For **output** values, add column name(s) that should be returned as `file-like` + objects to `.Cursor.stream_blobs` list attribute. Firebird-driver then returns + `.BlobReader` instance instead string in place of returned BLOB value for these column(s). + +!!! important + + The firebird-driver provides `.Cursor.stream_blob_threshold` attribute that controls + the maximum size of materialized blobs (as memory exhaustion safeguard). When particular + blob value exceeds this threshold, an instance of `.BlobReader` is returned instead + string/bytes value. + + Zero threshold value effectively forces all blobs to be returned as stream blobs. + Negative value means no size limit for materialized blobs (use at your own risk). + Please note that positive threshold value means that your application has to be + prepared to handle BLOBs in both incarnations. + + The default threshold is 64K and could be changed using `.DriverConfig.stream_blob_threshold` + configuration option. + + Blob size threshold has effect only on materialized blob columns, i.e. columns not + explicitly requested to be returned as streamed ones using `.Cursor.stream_blobs` + attribute, that are **always** returned as stream blobs. + +The `.BlobReader` instance is bound to `.Cursor` instance, and it's automatically closed +with cursor. However, it's good practice to use `with` statement or call `.BlobReader.close()` +once you're finished reading to release system resources associated with BLOB value. + +!!! important + + When working with BLOB values, always have memory efficiency in mind, especially when + you're processing huge quantity of rows with BLOB values at once. Materialized BLOB + values may exhaust your memory quickly, but using stream BLOBs may have inpact on + performance too, as new `.BlobReader` instance is created for each value fetched. + +**Example program:** + +```python +from firebird.driver import connect + +with connect('employee', user='SYSDBA', password='masterkey') as con: + cur = con.cursor() + print("Materialized retrieval (as str):") + cur.execute('select proj_id, proj_desc from project') + proj_id, proj_desc = cur.fetchone() + print(f"{proj_id=}, {proj_desc=}") + + print("\nStreaming retrieval (via BlobReader):") + cur.stream_blobs.append('PROJ_DESC') + cur.execute('select proj_id, proj_desc from project') + proj_id, proj_desc = cur.fetchone() + with proj_desc: + print(f"{proj_id=}, {proj_desc=}") + print(proj_desc.read()) + +``` + +Output: + +```text +Materialized retrieval (as str): +proj_id='VBASE', proj_desc='Design a video data base management system for\ncontrolling on-demand video distribution.\n' + +Streaming retrieval (via BlobReader): +proj_id='VBASE', proj_desc=BlobReader[size=89] +Design a video data base management system for +controlling on-demand video distribution. + +``` + +### Firebird ARRAY type + +Firebird-driver supports Firebird ARRAY data type. ARRAY values are represented as +Python lists. On input, the Python sequence (list or tuple) must be nested appropriately +if the array field is multi-dimensional, and the incoming sequence must not fall short +of its maximum possible length (it will not be “padded” implicitly–see below). On output, +the lists will be nested if the database array has multiple dimensions. + +!!! note + + Database arrays have no place in a purely relational data model, which requires that + data values be atomized (that is, every value stored in the database must be reduced + to elementary, non-decomposable parts). The Firebird implementation of database arrays, + like that of most relational database engines that support this data type, is fraught + with limitations. + + Database arrays are of fixed size, with a predeclared number of dimensions (max. 16) + and number of elements per dimension. Individual array elements cannot be set to + NULL / None, so the mapping between Python lists (which have dynamic length and are + therefore not normally “padded” with dummy values) and non-trivial database arrays is + clumsy. + + Stored procedures cannot have array parameters. + + Finally, many interface libraries, GUIs, and even the isql command line utility do not + support database arrays. + + In general, it is preferable to avoid using database arrays unless you have a compelling + reason. + +**Example:** + +```python +>>> from firebird.driver import connect +>>> con = connect('employee',user='sysdba', password='masterkey') +>>> cur = con.cursor() +>>> cur.execute("select LANGUAGE_REQ from job where job_code='Eng' and job_grade=3 and job_country='Japan'") +>>> cur.fetchone() +(['Japanese\n', 'Mandarin\n', 'English\n', '\n', '\n'],) + +``` + +**Example program:** + +```python +from firebird.driver import connect + +arrayIn = [ + [1, 2, 3, 4], + [5, 6, 7, 8], + [9,10,11,12] + ] + +with connect('/temp/test.db', user='sysdba', password='pass') as con: + con.execute_immediate("recreate table array_table (a int[3,4])") + con.commit() + + cur = con.cursor() + + print(f"{arrayIn=}") + cur.execute("insert into array_table values (?)", (arrayIn,)) + con.commit() + + cur.execute("select a from array_table") + arrayOut = cur.fetchone()[0] + print(f"{arrayOut=}) + +``` + +Output: + +```text +arrayIn=[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] +arrayOut=[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] + +``` + +## Transanction management + +For the sake of simplicity, firebird-driver lets the Python programmer ignore +transaction management to the greatest extent allowed by the Python Database +API Specification 2.0. The specification says, “if the database supports an +auto-commit feature, this must be initially off”. At a minimum, therefore, +it is necessary to call the commit method of the connection in order to persist +any changes made to the database. + +Remember that because of ACID, every data manipulation operation in the Firebird +database engine takes place in the context of a transaction, including operations +that are conceptually “read-only”, such as a typical SELECT. The client programmer +of firebird-driver establishes a transaction implicitly by using any SQL execution +method, such as `.Connection.execute_immediate()`, `.Cursor.execute()`, or +`.Cursor.callproc()`. + +Although firebird-driver allows the programmer to pay little attention to transactions, +it also exposes the full complement of the database engine’s advanced transaction +control features: [transaction parameters](usage-guide.md#transaction-parameters), [retaining transactions](usage-guide.md#retaining-transactions), [savepoints](usage-guide.md#savepoints), +and [distributed transactions](usage-guide.md#distributed-transactions). + +### Basics + +When it comes to transactions, Python Database API 2.0 specify that `.Connection` object +has to respond to the following methods: + +`.Connection.commit()` + + Commits any pending transaction to the database. Note that if the database supports + an auto-commit feature, this must be initially off. An interface method may be provided + to turn it back on. Database modules that do not support transactions should implement + this method with void functionality. + +`.Connection.rollback()` + + (optional) In case a database does provide transactions this method causes the the + database to roll back to the start of any pending transaction. **Closing a connection + without committing the changes first will cause an implicit rollback to be performed.** + +In addition to the implicit transaction initiation required by Python Database API, +firebird-driver allows the programmer to start transactions explicitly via the +`.Connection.begin()` method. Also `.Connection.savepoint()` method was added to provide +support for [Firebird SAVEPOINTs](http://www.firebirdsql.org/refdocs/langrefupd15-savepoint.html). + +But Python Database API 2.0 was created with assumption that connection can support only +one transactions per single connection. However, Firebird can support multiple independent +transactions that can run simultaneously within single connection / attachment to the +database. This feature is very important, as applications may require multiple transaction +opened simultaneously to perform various tasks, which would require to open multiple +connections and thus consume more resources than necessary. + +Firebird-driver surfaces this Firebird feature by separating transaction management out +from `.Connection` into separate `.TransactionManager` objects. To comply with Python DB +API 2.0 requirements, `.Connection` object uses one `.TransactionManager` instance as +`main transaction`, and delegates `~.Connection.begin()`, +`~.Connection.savepoint()`, `~.Connection.commit()`, `~.Connection.rollback()` and +`~.Connection.execute_immediate()` calls to it. + +!!! info + + More about using multiple transactions with the same connection in separate + [section](usage-guide.md#multiple_transactions). + +**Example:** + +```python +from firebird.driver import connect + +with connect('employee', user='SYSDBA', password='masterkey') as con: + cur = con.cursor() + + # Most minimalistic transaction management -> implicit start, only commit() and rollback() + # ======================================================================================== + # + # Transaction is started implicitly + cur.execute('insert into country values ('Oz','Crowns') + con.commit() # commits active transaction + # Again, transaction is started implicitly + cur.execute('insert into country values ('Barsoom','XXX') + con.rollback() # rolls back active transaction + cur.execute('insert into country values ('Pellucidar','Shells') + +# Commit was not performed before connection context was closed +# This will roll back the transaction because Python DB API 2.0 +# requires that closing connection with pending transaction must +# cause an implicit rollback + +``` + +!!! info + `.TransactionManager` for details. + + +### Auto-commit + +Firebird-driver doesn't support `auto-commit` feature directly, but developers +may achieve the similar result using `explicit` transaction start, taking advantage +of `.TransactionManager.default_action` and its default value (`~.DefaultAction.COMMIT`). + +**Example:** + +```python +from firebird.driver import connect + +with connect('employee', user='SYSDBA', password='masterkey') as con: + cur = con.cursor() + + con.begin() + cur.execute('insert into country values ('Oz','Crowns') + con.begin() # commits active transaction and starts new one + cur.execute('insert into country values ('Barsoom','XXX') + con.begin() # commits active transaction and starts new one + cur.execute('insert into country values ('Pellucidar','Shells') + + # However, commit is required before connection is closed, + # because Python DB API 2.0 requires that closing connection + # with pending transaction must cause an implicit rollback + con.commit() + +``` + + +### Transaction parameters + +The database engine offers the client programmer an optional facility called +`transaction parameter buffers` (TPBs) for tweaking the operating characteristics +of the transactions he initiates. These include characteristics such as whether +the transaction has read and write access to tables, or read-only access, and +whether or not other simultaneously active transactions can share table access +with the transaction. + +Transaction manager has `~.TransactionManager.default_tpb` attribute that can be +changed to set the default TPB to be used for all subsequent transactions started +by this manager. Also Connection have a `~.Connection.default_tpb` attribute, +but it's used to set the default TPB for all transactions managers subsequently +created for the connection (see `.Connection.transaction_manager()`). + +Alternatively, if the programmer only wants to set the TPB for a single transaction, +he can start a transaction explicitly via the `.Connection.begin()` or +`.TransactionManager.begin()` method and pass a TPB for that single transaction. + +The TPB is a `bytes` value constructed from various tags and binary values, as +defined by API. While you can construct the TPB manually, the firebird-driver +provides several convenient ways for TPB construction: + +1. The `.tpb()` function for simple TPBs. + +2. The `~firebird.driver.core.TPB` class for complex TPBs (including table reservation etc.). + +**Examples:** + +```python +from firebird.driver import tpb, TPB, Isolation, TraAccessMode, TableShareMode, TableAccessMode + +# Use tpb() if isolation, timeout and access_mode parameters are enough for you +simple_tpb = tpb(Isolation.READ_COMMITTED_READ_CONSISTENCY,100,TraAccessMode.WRITE) + +# Use TPB if you want additional parameters than isolation, timeout and access_mode +my_tpb = TPB(isolation=Isolation.SNAPSHOT, + access_mode=TraAccessMode.WRITE, + lock_timeout=100, + no_auto_undo=True, + auto_commit=True, + ignore_limbo=True) +my_tpb.reserve_table('MY_TABLE', TableShareMode.PROTECTED, TableAccessMode.LOCK_WRITE) +complex_tpb = my_tpb.get_buffer() + +``` + + +### Getting information about transaction + +!!! important + + Because the scope and type of transaction information depends on the version of the Firebird + server, this information is made available through a separate class + `.TransactionInfoProvider`. The `.TransactionManager.info` property provides access to + instance of `.TransactionInfoProvider` or it's **ancestor** class according to used + Firebird version. + +Although you may query the information directly from server using +`~.TransactionInfoProvider3.get_info()` method (that wraps the Firebird `ITransaction.getInfo()` +API call), the `.TransactionInfoProvider` object provides more convenient methods and properties +for obtaining specific information directly. + +**Example:** + +```python +from firebird.driver import connect, driver_config + +driver_config.server_defaults.host.value = 'localhost' +with connect('employee', user='SYSDBA', password='masterkey') as con: + con.begin() + info = con.main_transaction.info + print(f"Transaction ID: {info.id}") + print(f"Database: {info.database}") + print(f"Isolation level: {info.isolation!s}") + print(f"Lock timeout: {info.lock_timeout}") + print(f"Is Read-Only: {info.is_read_only()}") + print(f"ID of Oldest Interesting Transaction: {info.oit}") + print(f"ID of Oldest Active Transaction: {info.oat}") + print(f"ID of Oldest Snapshot Transaction: {info.ost}") + +``` + +Output: + +```text +Transaction ID: 352 +Database: localhost:employee +Isolation level: Isolation.SNAPSHOT +Lock timeout: -1 +Is Read-Only: False +ID of Oldest Interesting Transaction: 350 +ID of Oldest Active Transaction: 352 +ID of Oldest Snapshot Transaction: 352 + +``` + +### Retaining transactions + +The `~.TransactionManager.commit()` and `~.TransactionManager.rollback()` methods +accept an optional boolean keyword parameter `retaining` (**default False**) to +indicate whether to recycle the transactional context of the transaction being resolved +by the method call. + +If retaining is `True`, the infrastructural support for the transaction active at +the time of the method call will be “retained” (efficiently and transparently recycled) +after the database server has committed or rolled back the conceptual transaction. + +!!! important + + In code that commits or rolls back frequently in short amount of time (like in loop), + “retaining” the transaction may yield better performance. However, retaining transactions + must be used cautiously because they can interfere with the server’s ability to garbage + collect old record versions. For details about this issue, read the “Garbage” section of + [this document](http://www.ibphoenix.com/resources/documents/search/doc_21) by Ann Harrison. + + It's definitely no recommended to use retaining for all transactions, or retain the transaction + context indefinitely (you should eventually commit/rollback the transaction in normal + way). + +For more information about retaining transactions, see `Firebird documentation`. + + +### Savepoints + +Savepoints are named, intermediate control points within an open transaction that +can later be rolled back to, without affecting the preceding work. Multiple savepoints +can exist within a single unresolved transaction, providing “multi-level undo” functionality. + +Although Firebird savepoints are fully supported from SQL alone via the `SAVEPOINT ‘name’` +and `ROLLBACK TO ‘name’` statements, firebird-driver also exposes savepoints at the Python +API level for the sake of convenience. + +Call to method `.TransactionManager.savepoint()` establishes a savepoint with the specified +`name`. To roll back to a specific savepoint, call the `~.TransactionManager.rollback()` +method and provide the name of the savepoint for the `savepoint` keyword parameter. If the +savepoint parameter of `~.TransactionManager.rollback()` is not specified, the active +transaction is cancelled in its entirety, as required by the Python Database API Specification. + +The following program demonstrates savepoint manipulation via the firebird-driver API, +rather than raw SQL. + +```python +from firebird.driver import connect + +with connect('employee', user='SYSDBA', password='masterkey') as con: + cur = con.cursor() + + cur.execute("recreate table test_savepoints (a integer)") + con.commit() + + print('Before the first savepoint, the contents of the table are:') + cur.execute("select * from test_savepoints") + print(' ', cur.fetchall()) + + cur.execute("insert into test_savepoints values (?)", [1]) + con.savepoint('A') + print('After savepoint A, the contents of the table are:') + cur.execute("select * from test_savepoints") + print(' ', cur.fetchall()) + + cur.execute("insert into test_savepoints values (?)", [2]) + con.savepoint('B') + print('After savepoint B, the contents of the table are:') + cur.execute("select * from test_savepoints") + print(' ', cur.fetchall()) + + cur.execute("insert into test_savepoints values (?)", [3]) + con.savepoint('C') + print('After savepoint C, the contents of the table are:') + cur.execute("select * from test_savepoints") + print(' ', cur.fetchall()) + + con.rollback(savepoint='B') + print('After rolling back to savepoint B, the contents of the table are:') + cur.execute("select * from test_savepoints") + print(' ', cur.fetchall()) + + con.rollback() + print('After rolling back entirely, the contents of the table are:') + cur.execute("select * from test_savepoints") + print(' ', cur.fetchall()) + +``` + +The output of the example program is shown below: + +```text +Before the first savepoint, the contents of the table are: + [] +After savepoint A, the contents of the table are: + [(1,)] +After savepoint B, the contents of the table are: + [(1,), (2,)] +After savepoint C, the contents of the table are: + [(1,), (2,), (3,)] +After rolling back to savepoint B, the contents of the table are: + [(1,), (2,)] +After rolling back entirely, the contents of the table are: + [] + +``` + + + +### Using multiple transactions with the same connection + +To use additional transactions that could run simultaneously with +`main transaction` managed by `.Connection`, +create new `.TransactionManager` object calling `.Connection.transaction_manager()` +method. If you don't specify the optional `default_tpb` parameter, this new +`.TransactionManager` inherits the `~.Connection.default_tpb` from `.Connection`. +Physical transaction is not started when `.TransactionManager` instance is +created, but implicitly when first SQL statement for cursor created from +this manager is executed, or explicitly via `.TransactionManager.begin()` call. + +To execute statements in context of this additional transaction you have to +use `cursors` obtained directly from this `.TransactionManager` instance calling +its `~.TransactionManager.cursor()` method, or call `.TransactionManager.execute_immediate()` +method. + +**Example:** + +```python +from firebird.driver import connect, tpb, Isolation, TraAccessMode + +with connect('employee', user='SYSDBA', password='masterkey') as con: + # Cursor for main_transaction context + cur = con.cursor() + + # Create new READ ONLY READ COMMITTED transaction + ro_transaction = con.transaction_manager(tpb(Isolation.READ_COMMITTED_RECORD_VERSION, + access=TraAccessMode.READ)) + # and cursor + ro_cur = ro_transaction.cursor() + + cur.execute('insert into country values ('Oz','Crowns') + con.commit() # commits main transaction + + # Read data created by main transaction from second one + ro_cur.execute("select * from COUNTRY where COUNTRY = `Oz`") + print(ro_cur.fetchall()) + + # Insert more data, but don't commit + cur.execute('insert into country values ('Barsoom','XXX') + + # Read data created by main transaction from second one + ro_cur.execute("select * from COUNTRY where COUNTRY = `Barsoom`") + print(ro_cur.fetchall()) + +``` + + + + +### Distributed Transactions + +Distributed transactions are transactions that span multiple databases. +Firebird-driver provides this Firebird feature through `.DistributedTransactionManager` +class. Instances of this class must be created manually, and managed transactions +are fully independent from all other transactions, main or secondary, of member connections. + +Similarly to `.TransactionManager`, distributed transactions are managed +through `~.DistributedTransactionManager.begin()`, +`~.DistributedTransactionManager.savepoint()`, `~.DistributedTransactionManager.commit()` +and `~.DistributedTransactionManager.rollback()` methods. +Additionally, `.DistributedTransactionManager` exposes method +`~.DistributedTransactionManager.prepare()` that explicitly initiates the +first phase of `Two-Phase Commit Protocol`. Transaction parameters are defined +similarly to `.TransactionManager` using `~.DistributedTransactionManager.default_tpb` +or as optional parameter to `~.DistributedTransactionManager.begin()` call. + +SQL statements that should belong to context of distributed transaction are +executed via `.Cursor` instances aquired through `.DistributedTransactionManager.cursor()` +method, or calling `.DistributedTransactionManager.execute_immediate()` method. + +!!! note + + Because `.Cursor` instances can belong to only one `.Connection`, the + `~.DistributedTransactionManager.cursor()` method has mandatory parameter + `connection`, to specify to which member connection cursor should belong. + + The `~.DistributedTransactionManager.execute_immediate()` method operates + on **all** databases in *group*. + +**Example program:** + +```python +from firebird.driver import create_database, DistributedTransactionManager + +# First database +con1 = create_database('db1.fdb', user='SYSDBA', password='masterkey') +con1.execute_immediate("recreate table T (PK integer, C1 integer)") +con1.commit() + +# Second database +con2 = create_database('db2.fdb', user='SYSDBA', password='masterkey') +con2.execute_immediate("recreate table T (PK integer, C1 integer)") +con2.commit() + +# Create distributed transaction manager +dt = DistributedTransactionManager((con1,con2)) + +# Prepare cursors for each connection +dc1 = dt.cursor(con1) +dc2 = dt.cursor(con2) + +# Connection cursors to check content of databases +q = 'select * from T order by pk' + +cc1 = con1.cursor() +p1 = cc1.prep(q) + +cc2 = con2.cursor() +p2 = cc2.prep(q) + +print("Distributed transaction: COMMIT") +# =============================== +dc1.execute('insert into t (pk) values (1)') +dc2.execute('insert into t (pk) values (1)') +dt.commit() + +# check it +con1.commit() +cc1.execute(p1) +print('db1:', cc1.fetchall()) +con2.commit() +cc2.execute(p2) +print('db2:', cc2.fetchall()) + +print("Distributed transaction: PREPARE + COMMIT") +# ========================================= +dc1.execute('insert into t (pk) values (2)') +dc2.execute('insert into t (pk) values (2)') +dt.prepare() +dt.commit() + +# check it +con1.commit() +cc1.execute(p1) +print('db1:', cc1.fetchall()) +con2.commit() +cc2.execute(p2) +print('db2:', cc2.fetchall()) + +print("Distributed transaction: SAVEPOINT + ROLLBACK to it") +# =================================================== +dc1.execute('insert into t (pk) values (3)') +dt.savepoint('CG_SAVEPOINT') +dc2.execute('insert into t (pk) values (3)') +dt.rollback(savepoint='CG_SAVEPOINT') + +# check it - via group cursors, as transaction is still active +dc1.execute(q) +print('db1:', dc1.fetchall()) +dc2.execute(q) +print('db2:', dc2.fetchall()) + +print("Distributed transaction: ROLLBACK") +# ================================= +dt.rollback() + +# check it +con1.commit() +cc1.execute(p1) +print('db1:', cc1.fetchall()) +con2.commit() +cc2.execute(p2) +print('db2:', cc2.fetchall()) + +print("Distributed transaction: EXECUTE_IMMEDIATE") +# ========================================== +dt.execute_immediate('insert into t (pk) values (3)') +dt.commit() + +# check it +con1.commit() +cc1.execute(p1) +print('db1:', cc1.fetchall()) +con2.commit() +cc2.execute(p2) +print('db2:', cc2.fetchall()) + +# Finalize +con1.drop_database() +con1.close() +con2.drop_database() +con2.close() + +``` + +Output: + +```text +Distributed transaction: COMMIT +db1: [(1, None)] +db2: [(1, None)] +Distributed transaction: PREPARE + COMMIT +db1: [(1, None), (2, None)] +db2: [(1, None), (2, None)] +Distributed transaction: SAVEPOINT + ROLLBACK to it +db1: [(1, None), (2, None), (3, None)] +db2: [(1, None), (2, None)] +Distributed transaction: ROLLBACK +db1: [(1, None), (2, None)] +db2: [(1, None), (2, None)] +Distributed transaction: EXECUTE_IMMEDIATE +db1: [(1, None), (2, None), (3, None)] +db2: [(1, None), (2, None), (3, None)] + +``` + + + +### Transaction Context Manager + +Firebird-driver provides context manager `~firebird.driver.core.transaction` that allows automatic +transaction management using WITH statement. It can work with +any object that supports `begin()`, `commit()` and `rollback()` methods, i.e. +`.Connection`, `.TransactionManager` or `.DistributedTransactionManager`. + +It starts transaction when WITH block is entered and commits it if no exception +occurs within it, or calls `rollback()` otherwise. Exceptions raised in WITH +block are never suppressed. + +Examples: + +```python +from firebird.driver import connect, transaction, DistributedTransactionManager + +with connect('employee', user='SYSDBA', password='masterkey') as con: + + # Uses default main transaction + with transaction(con): + cur = con.cursor() + cur.execute("insert into T (PK,C1) values (1,'TXT')") + + # Uses separate transaction + with transaction(con.transaction_manager()) as tr: + cur = tr.cursor() + cur.execute("insert into T (PK,C1) values (2,'AAA')") + + # Uses distributed transaction + with connect('employee2', user='SYSDBA', password='masterkey') as con2, + DistributedTransactionManager(con, con2) as dtm: + with transaction(dtm): + cur1 = cg.cursor(con) + cur2 = cg.cursor(con2) + cur1.execute("insert into T (PK,C1) values (3,'Local')") + cur2.execute("insert into T (PK,C1) values (3,'Remote')") + +``` + + +## Database Events + +### What they are +The Firebird engine features a distributed, inter-process communication mechanism based on +messages called `database events`. A database event is a message passed from a trigger or +stored procedure to an application to announce the occurrence of a specified condition or +action, usually a database change such as an insertion, modification, or deletion of a record. +The Firebird event mechanism enables applications to respond to actions and database changes +made by other, concurrently running applications without the need for those applications to +communicate directly with one another, and without incurring the expense of CPU time +required for periodic polling to determine if an event has occurred. + +### Why use them +Anything that can be accomplished with database events can also be implemented using other +techniques, so why bother with events? Since you’ve chosen to write database-centric programs +in Python rather than assembly language, you probably already know the answer to this question, +but let’s illustrate. + +A typical application for database events is the handling of administrative messages. +Suppose you have an administrative message database with a `message's` table, into which +various applications insert timestamped status reports. It may be desirable to react to +these messages in diverse ways, depending on the status they indicate: to ignore them, to +initiate the update of dependent databases upon their arrival, to forward them by e-mail +to a remote administrator, or even to set off an alarm so that on-site administrators will +know a problem has occurred. + +It is undesirable to tightly couple the program whose status is being reported +(the `message producer`) to the program that handles the status reports (the `message handler`). +There are obvious losses of flexibility in doing so. For example, the message producer may +run on a separate machine from the administrative message database and may lack access rights +to the downstream reporting facilities (e.g., network access to the SMTP server, in the case +of forwarded e-mail notifications). Additionally, the actions required to handle status +reports may themselves be time-consuming and error-prone, as in accessing a remote network +to transmit e-mail. + +In the absence of database event support, the message handler would probably be implemented +via `polling`. Polling is simply the repetition of a check for a condition at a specified +interval. In this case, the message handler would check in an infinite loop to see whether +the most recent record in the `messages` table was more recent than the last message it had +handled. If so, it would handle the fresh message(s); if not, it would go to sleep for +a specified interval, then loop. + +The `polling-based` implementation of the message handler is fundamentally flawed. Polling +is a form of [busy-wait](http://www.catb.org/jargon/html/B/busy-wait.html); the check for new messages is performed at the specified interval, +regardless of the actual activity level of the message producers. If the polling interval +is lengthy, messages might not be handled within a reasonable time period after their arrival; +if the polling interval is brief, the message handler program (and there may be many such +programs) will waste a large amount of CPU time on unnecessary checks. + +The database server is necessarily aware of the exact moment when a new message arrives. +Why not let the message handler program request that the database server send it a notification +when a new message arrives? The message handler can then efficiently sleep until the moment +its services are needed. Under this `event-based` scheme, the message handler becomes +aware of new messages at the instant they arrive, yet it does not waste CPU time checking +in vain for new messages when there are none available. + +### How events are exposed + +1. Server Process ("An event just occurred!") + + To notify any interested listeners that a specific event has + occurred, issue the `POST_EVENT` statement from Stored Procedure + or Trigger. The `POST_EVENT` statement has one parameter: the name + of the event to post. In the preceding example of the administrative + message database, `POST_EVENT` might be used from an `after insert` + trigger on the `messages` table, like this: + + ```sql + create trigger trig_messages_handle_insert + for messages + after insert + as + begin + POST_EVENT 'new_message'; + end + + ``` + + !!! note + The physical notification of the client process does not + + occur until the transaction in which the `POST_EVENT` took place is + actually committed. Therefore, multiple events may *conceptually* + occur before the client process is *physically* informed of even one + occurrence. Furthermore, the database engine makes no guarantee that + clients will be informed of events in the same groupings in which they + conceptually occurred. If, within a single transaction, an event named + `event_a` is posted once and an event named `event_b` is posted once, + the client may receive those posts in separate "batches", despite the + fact that they occurred in the same conceptual unit (a single + transaction). This also applies to multiple occurrences of *the same* + event within a single conceptual unit: the physical notifications may + arrive at the client separately. + +1. Client Process ("Send me a message when an event occurs.") + + !!! note + If you don't care about the gory details of event notification, + + skip to the section that describes FDB's Python-level event handling + API. + + The Firebird C client library offers two forms of event notification. + The first form is *synchronous* notification, by way of the function + `isc_wait_for_event()`. This form is admirably simple for a C programmer + to use, but is inappropriate as a basis for FDB's event support, + chiefly because it's not sophisticated enough to serve as the basis for + a comfortable Python-level API. The other form of event notification + offered by the database client library is *asynchronous*, by way of the + functions `isc_que_events()` (note that the name of that function + is misspelled), `isc_cancel_events()`, and others. The details are + as nasty as they are numerous, but the essence of using asynchronous + notification from C is as follows: + + 1. Call `isc_event_block()` to create a formatted binary buffer that will tell + the server which events the client wants to listen for. + 1. Call `isc_que_events()` (passing the buffer created in the previous step) to + inform the server that the client is ready to receive event notifications, and provide + a callback that will be asynchronously invoked when one or more of the registered events occurs. + 1. [The thread that called `isc_que_events()` to initiate event listening must + now do something else.] + 1. When the callback is invoked (the database client library starts a thread dedicated + to this purpose), it can use the `isc_event_counts()` function to determine + how many times each of the registered events has occurred since the last call to + `isc_event_counts()` (if any). + 1. [The callback thread should now "do its thing", which may include communicating with + the thread that called `isc_que_events()`.] + 1. When the callback thread is finished handling an event notification, it must call + `isc_que_events()` again in order to receive future notifications. Future + notifications will invoke the callback again, effectively "looping" the callback + thread back to Step 4. + +### API for Python developers + +The Firebird-driver database event API is comprised of the following: the method +`.Connection.event_collector()` and the class `.EventCollector`. + +Use the `.Connection.event_collector()` method (takes a sequence of string event +names as parameter) to create `.EventCollector` instance, that collects database event +notifications sent from the server for given database. + +!!! important + + To start listening for events it's necessary to call `.EventCollector.begin()` + method or use EventCollector's context manager interface. + +Immediately when `~.EventCollector.begin()` method is called, EventCollector starts +to accumulate notifications of any event that occur within the collector’s internal queue +until the collector is closed either explicitly (via the `~.EventCollector.close()` +method) or implicitly (via garbage collection). + +Notifications about events are aquired through call to `~.EventCollector.wait()` method, +that blocks the calling thread until at least one of the events occurs, or the specified +`timeout` (if any) expires, and returns `None` if the wait timed out, or a dictionary that +maps `event_name -> event_occurrence_count`. + +!!! important + + `.EventCollector` can act as context manager that ensures execution of + `~.EventCollector.begin()` and `~.EventCollector.close()` methods. + It's strongly advised to use the `.EventCollector` with the `with` statement. + +**Example:** + +```python +with connection.event_collector(['event_a', 'event_b']) as collector: + events = collector.wait() + process_events(events) + +``` + +If you want to drop notifications accumulated so far by conduit, call +`.EventCollector.flush()` method. + +**Example program:** + +```python +from firebird.driver import create_database, transaction +import threading +import time + +# Prepare database +con = create_database('event-test', user='SYSDBA', password='masterkey') +with transaction(con): + con.execute_immediate("CREATE TABLE T (PK Integer, C1 Integer)") + con.execute_immediate("""CREATE TRIGGER EVENTS_AU FOR T ACTIVE + BEFORE UPDATE POSITION 0 + AS + BEGIN + if (old.C1 <> new.C1) then + post_event 'c1_updated' ; + END""") + con.execute_immediate("""CREATE TRIGGER EVENTS_AI FOR T ACTIVE + AFTER INSERT POSITION 0 + AS + BEGIN + if (new.c1 = 1) then + post_event 'insert_1' ; + else if (new.c1 = 2) then + post_event 'insert_2' ; + else if (new.c1 = 3) then + post_event 'insert_3' ; + else + post_event 'insert_other' ; + END""") +cur = con.cursor() + +# Utility function +def send_events(command_list): + with transaction(con): + for cmd in command_list: + cur.execute(cmd) + +print("One event") +# ========= +timed_event = threading.Timer(3.0,send_events,args=[["insert into T (PK,C1) values (1,1)",]]) +with con.event_collector(['insert_1']) as events: + timed_event.start() + e = events.wait() +print(e) + +print("Multiple events") +# =============== +cmds = ["insert into T (PK,C1) values (1,1)", + "insert into T (PK,C1) values (1,2)", + "insert into T (PK,C1) values (1,3)", + "insert into T (PK,C1) values (1,1)", + "insert into T (PK,C1) values (1,2)",] +timed_event = threading.Timer(3.0,send_events,args=[cmds]) +with con.event_collector(['insert_1','insert_3']) as events: + timed_event.start() + e = events.wait() +print(e) + +print("20 events") +# ========= +cmds = ["insert into T (PK,C1) values (1,1)", + "insert into T (PK,C1) values (1,2)", + "insert into T (PK,C1) values (1,3)", + "insert into T (PK,C1) values (1,1)", + "insert into T (PK,C1) values (1,2)",] +timed_event = threading.Timer(1.0,send_events,args=[cmds]) +with con.event_collector(['insert_1','A','B','C','D', + 'E','F','G','H','I','J','K','L','M', + 'N','O','P','Q','R','insert_3']) as events: + timed_event.start() + time.sleep(3) + e = events.wait() +print(e) + +print("Flush events") +# ============ +timed_event = threading.Timer(3.0,send_events,args=[["insert into T (PK,C1) values (1,1)",]]) +with con.event_collector(['insert_1']) as events: + send_events(["insert into T (PK,C1) values (1,1)", + "insert into T (PK,C1) values (1,1)"]) + time.sleep(2) + events.flush() + timed_event.start() + e = events.wait() +print(e) + +# Finalize +con.drop_database() +con.close() + +``` + +Output: + +```text +One event +{'insert_1': 1} +Multiple events +{'insert_3': 1, 'insert_1': 2} +20 events +{'A': 0, 'C': 0, 'B': 0, 'E': 0, 'D': 0, 'G': 0, 'insert_1': 2, 'I': 0, 'H': 0, 'K': 0, 'J': 0, 'M': 0, + 'L': 0, 'O': 0, 'N': 0, 'Q': 0, 'P': 0, 'R': 0, 'insert_3': 1, 'F': 0} +Flush events +{'insert_1': 1} + +``` + + + + +## Working with Services + +Database server maintenance tasks such as user management, load monitoring, +and database backup have traditionally been automated by scripting the +command-line tools `gbak`, `gfix`, `gsec`, and `gstat`. + +The API presented to the client programmer by these utilities is inelegant +because they are, after all, command-line tools rather than native components +of the client language. To address this problem, Firebird has a facility called +the `Services API`, which exposes a uniform interface to the administrative +functionality of the traditional command-line tools. + +The native Services API, though consistent, is much lower-level than a Pythonic API. +If the native version were exposed directly, accomplishing a given task would probably +require more Python code than scripting the traditional command-line tools. For this +reason, the firebird-driver presents its own abstraction over the native API. + + +### Services API Connections + +All Services API operations are performed in the context of a `connection` to a specific +database server, represented by the `.Server` class. Similarly to database connections, +firebird-driver provides `.connect_server()` constructor function to create such connections. + +This constructor has one positional and several keyword parameters. + +The value of `server` positional parameter must be one of: + +* name of registered server configuration +* server host name or address + +Keyword parameters are intended to override selected configuration options, or to specify +options that are not configurable. + +A simple server connection is typically established with code such as this: + +```python +from firebird.driver import connect_server + +# Attach to 'embedded' server +srv = connect_server('', user='SYSDBA', password='masterkey') + +# Attach to 'local' server +srv = connect_server('localhost', user='SYSDBA', password='masterkey') + +# Set 'user' and 'password' via configuration +from firebird.driver import driver_config +driver_config.server_defaults.user.value = 'SYSDBA' +driver_config.server_defaults.password.value = 'masterkey' +srv = connect_server('localhost') + +``` + +However, it's recommended to use specific configuration for servers. +It's possible to register servers directly in code like this: + +```python +from firebird.driver import connect_server, driver_config + +# Register Firebird server +srv_cfg = """[main_server] +host = 192.168.0.15 +user = SYSDBA +password = Xyzzy +""" +driver_config.register_server('main_server', srv_cfg) + +# Attach to 'main' server +con = connect('main_server') + +``` + +But more convenient approach is using single configuration file: + +```text +# file: myapp.cfg + +[firebird.driver] +servers = main_server +databases = employee + +[main_server] +host = 192.168.0.15 +user = SYSDBA +password = Xyzzy + +``` + +```python +from firebird.driver import connect_server, driver_config + +driver_config.read('myapp.cfg') + +# Attach to 'main' server +con = connect('main_server') + +``` + +!!! note + + Like database connections, it's important to properly `~Server.close()` them + when you don't need them anymore. + +`.Server` object provides main infrastructure for communication with Firebird server services, +and manages number of objects that provide actual server services: + +* The `.Server.info` property object provides [Server Configuration and State information](usage-guide.md#server-configuration-and-state-information). +* The `.Server.database` property object provides [Database options](usage-guide.md#database-options) and [Database maintenance](usage-guide.md#database-maintenance). +* The `.Server.user` property object provides [User maintenance](usage-guide.md#user-maintenance). +* The `.Server.trace` property object provides management of [Trace sessions](usage-guide.md#trace-sessions). + +!!! info + `.connect_server()` and `.Server` for details. + + +### Text output from Services + +Some services like `.ServerDbServices.backup()` may return significant amount of text. +Rather than return the whole text as single string value by methods that provide access +to these services, firebird-driver isolated the transfer process to separate methods: + +* `~.Server.readline()` - Similar to `file.readline`, returns next line of output from Service. +* `~.Server.readline_timed()` - Like `~.Server.readline()` but with timeout. +* `~.Server.readlines()` - Like `file.readlines`, returns list of output lines. +* Iteration over `.Server` object, because `.Server` has built-in support for [iterator protocol](https://docs.python.org/3/library/stdtypes.html#iterator-types). +* Using `callback` method provided by developer. Each `.Server` method that returns its result + asynchronously accepts an optional parameter `callback`, which must be a function that accepts + one string parameter. This method is then called with each output line coming from service. +* `~.Server.wait()` - Waits for Sevice to finish, ignoring rest of the output it may produce. + +!!! important + + The Firebird server sends text output from services as packets, that could have two forms. + The method for packet construction used for text transfer is controlled by `.Server.mode` + attribute with next possible values: + + 1. `.SrvInfoCode.LINE` : A single line of text. + 2. `.SrvInfoCode.TO_EOF` : A block of text up to specified (buffer) size. + + Both methods have specific pros and cons: + + 1. `~.SrvInfoCode.LINE` means more roundtrips and thus slower transfer of service output, + but each line is sent to client immediately when it's available. + 2. `~.SrvInfoCode.TO_EOF` means fewer roundtrips so large output is transferred quickly, + but service output is not sent until the transfer buffer is not full, or service stops. + + **The default mode is** `~.SrvInfoCode.TO_EOF` **with 64K buffer.** + +!!! warning + + Until output is not fully fetched from service, any attempt to start another asynchronous + service will fail with exception! This constraint is set by Firebird Service API. + + You may check the status of asynchronous Services using `.Server.is_running()` method. + + In cases when you're not interested in output produced by Service, call `~.Server.wait()` + to wait for service to complete. + +!!! important + + Normally, requesting output with `~.Server.readline()` blocks until any output is + available from server. Bacuse this method is used by iteration over `.Server` and + `~.Server.readlines()` method, they will block as well. Most services produce output + continuously and without (much) delay, so this is usually not a problem. However, some + services (eg trace) can produce output at significantly slower intervals (if at all), + which complicates the creation of responsive applications. In this case, it is necessary + to use the `~.Server.readline_timed()` method, which allows you to limit the waiting + time for the output. + +**Examples:** + +```python +from firebird.driver import connect_server +with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + print("Fetch materialized") + print("==================") + print("Start backup") + srv.database.backup(database='employee', backup='employee.fbk') + print("srv.running is", srv.isrunning()) + report = srv.readlines() + print(f"{len(report)} lines returned") + print("First 5 lines from output:") + for i in xrange(5): + print(i,report[i]) + print("srv.running is", srv.isrunning()) + print() + print("Iterate over result") + print("===================") + srv.database.backup(database='employee', backup='employee.fbk') + output = [] + for line in srv: + output.append(line) + print(f"{len(output)} lines returned") + print("Last 5 lines from output:") + for line in output[-5:]: + print(line) + print() + print("Callback") + print("========") + + output = [] + + # Callback function + def fetchline(line): + output.append(line) + + srv.database.backup(database='employee', backup='employee.fbk', callback=fetchline) + print(f"{len(output)} lines returned") + print("Last 5 lines from output:") + for line in output[-5:]: + print(line) + +``` + +Output: + +```text +Fetch materialized +================== +Start backup +svc.running is True +558 lines returned +First 5 lines from output: +0 gbak:readied database employee for backup +1 gbak:creating file employee.fbk +2 gbak:starting transaction +3 gbak:database employee has a page size of 4096 bytes. +4 gbak:writing domains +svc.running is False + +Iterate over result +=================== +558 lines returned +Last 5 lines from output: +gbak:writing referential constraints +gbak:writing check constraints +gbak:writing SQL roles +gbak:writing names mapping +gbak:closing file, committing, and finishing. 74752 bytes written + +Callback +======== +558 lines returned +Last 5 lines from output: +gbak:writing referential constraints +gbak:writing check constraints +gbak:writing SQL roles +gbak:writing names mapping +gbak:closing file, committing, and finishing. 74752 bytes written + +``` + +### Server Configuration and State information + +!!! important + + Because the scope and type of service information depends on the version of the Firebird + server, this information is made available through a separate class + `.ServerInfoProvider`. The `.Server.info` property provides access to + instance of `.ServerInfoProvider` or it's **ancestor** class according to attached + Firebird server version. + +`.ServerInfoProvider` methods and properties: + +* `~.ServerInfoProvider.get_log()` - Request the contents of the server’s log file (`firebird.log`). + + This method is so-called `Async service` that only initiates log transfer. Actual log + content could be read by one from many methods for [text output from Services](usage-guide.md#text-output-from-services) that + `.Server` provides . + +* `~.ServerInfoProvider.version` - Returns Firebird server version as SEMVER string. + +* `~.ServerInfoProvider.engine_version` - Firebird server version as . float value. + +* `~.ServerInfoProvider.manager_version` - Firebird service manager version. + +* `~.ServerInfoProvider.architecture` - Firebird server implementation description. + +* `~.ServerInfoProvider.home_directory` - Firebird server home directory. + +* `~.ServerInfoProvider.security_database` - Security database. + +* `~.ServerInfoProvider.lock_directory` - Directory with lock file(s). + +* `~.ServerInfoProvider.message_directory` - Directory with message file(s). + +* `~.ServerInfoProvider.capabilities` - Firebird server capabilities (as `.ServerCapability` flags). + +* `~.ServerInfoProvider.connection_count` - Current number of database attachments. + +* `~.ServerInfoProvider.attached_databases` - List of attached databases. + +**Example:** + +```python +from firebird.driver import driver_config, connect, connect_server + +srv_cfg = """[local] +host = localhost +user = SYSDBA +password = masterkey +""" +driver_config.register_server('local', srv_cfg) +db_cfg = """[employee] +server = local +database = employee.fdb +protocol = inet +""" +driver_config.register_database('employee', db_cfg) +with connect('employee', user='SYSDBA', password='masterkey'), connect_server('local', user='SYSDBA', password='masterkey') as srv: + print(f'{srv.info.version=}') + print(f'{srv.info.engine_version=}') + print(f'{srv.info.manager_version=}') + print(f'{srv.info.architecture=}') + print(f'{srv.info.home_directory=}') + print(f'{srv.info.security_database=}') + print(f'{srv.info.lock_directory=}') + print(f'{srv.info.message_directory=}') + print(f'{srv.info.capabilities=!s}') + print(f'{srv.info.connection_count=}') + print(f'{srv.info.attached_databases=}') + +``` + +Sample output for 64-bit Linux Firebird 4.0 Beta 2: + +```text +srv.info.version='4.0.0.1963' +srv.info.engine_version=4.0 +srv.info.manager_version=2 +srv.info.architecture='Firebird/Linux/AMD/Intel/x64' +srv.info.home_directory='/opt/firebird/' +srv.info.security_database='/opt/firebird/security4.fdb' +srv.info.lock_directory='/tmp/firebird/' +srv.info.message_directory='/opt/firebird/' +srv.info.capabilities=ServerCapability.REMOTE_HOP|MULTI_CLIENT +srv.info.connection_count=1 +srv.info.attached_databases=['/opt/firebird/examples/empbuild/employee.fdb'] + +``` + +### Database options + +Database options could be set using `.ServerDbServices` instance accessible via +`.Server.database` property. + +* `~.ServerDbServices.set_default_cache_size()` - Sets individual page cache size for database. + + ```python + >>> from firebird.driver import connect_server + >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + >>> srv.database.set_default_cache_size(database='employee.fdb', size=5000) + + ``` + +* `~.ServerDbServices.set_sweep_interval()` - Sets database sweep interval. + + ```python + >>> from firebird.driver import connect_server + >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + >>> srv.database.set_sweep_interval(database='employee.fdb', interval=100000) + + ``` + +* `~.ServerDbServices.set_space_reservation()` - Sets space reservation option for database. + + ```python + >>> from firebird.driver import connect_server, DbSpaceReservation + >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + >>> srv.database.set_space_reservation(database='employee.fdb', mode=DbSpaceReservation.USE_FULL) + + ``` + +* `~.ServerDbServices.set_write_mode()` - Sets database write mode (SYNC/ASYNC). + + ```python + >>> from firebird.driver import connect_server, DbWriteMode + >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + >>> srv.database.set_write_mode(database='employee.fdb', mode=DbWriteMode.ASYNC) + + ``` + +* `~.ServerDbServices.set_access_mode()` - Sets database access mode (R/W or R/O). + + ```python + >>> from firebird.driver import connect_server, DbAccessMode + >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + >>> srv.database.set_access_mode(database='employee.fdb', mode=DbAccessMode.READ_ONLY) + + ``` + +* `~.ServerDbServices.set_sql_dialect()` - Sets database SQL dialect. + + !!! warning + + Changing SQL dialect on existing database is not recommended. Only newly created + database objects would respect new dialect setting, while objects created with + previous dialect remain unchanged. That may have dire consequences. + + ```python + >>> from firebird.driver import connect_server + >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + >>> srv.database.set_sql_dialect(database='employee.fdb', dialect=1) + + ``` + +* `~.ServerDbServices.no_linger()` - Sets one-off override for database linger. + + ```python + >>> from firebird.driver import connect_server + >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + >>> srv.database.no_linger(database='employee.fdb') + + ``` + + +### Database maintenance + +!!! important + + Because available database-related actions depends on the version of the Firebird + server, they are made available through a separate class `.ServerDbServices`. + The `.Server.database` property provides access to instance of `.ServerDbServices` or + it's **ancestor** class according to attached Firebird server version. + +* `~.ServerDbServices3.get_statistics()` - Returns database statistics produced by gstat + utility. + + This method is so-called `Async service` that only initiates report processing. Actual + report content could be read by one from many methods for [text output from Services](usage-guide.md#text-output-from-services) that + `.Server` provides . + + ```python + from firebird.driver import connect_server, SrvStatFlag + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.get_statistics(database='employee.fdb', + flags=SrvStatFlag.DATA_PAGES | SrvStatFlag.RECORD_VERSIONS), + tables=['EMPLOYEE','PROJECT']) + stats = srv.readlines() + + ``` + +* `~.ServerDbServices3.backup()` - Performs logical (GBAK) database backup. + + This method is so-called `Async service` that only initiates the backup process. Output + from gbak could be read by one from many methods for [text output from Services](usage-guide.md#text-output-from-services) that + `.Server` provides . + + ```python + from firebird.driver import connect_server, SrvBackupFlag + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.backup(database='employee.fdb', + backup='/backup/employee.fbk', + flags=SrvBackupFlag.IGNORE_CHECKSUMS | SrvBackupFlag.NO_GARBAGE_COLLECT, + stats='TD', verbose=True) + report = srv.readlines() + + ``` + +* `~.ServerDbServices3.local_backup()` - Performs logical (GBAK) database backup into local byte + stream. + + ```python + from firebird.driver import connect_server, SrvBackupFlag + f = open('/backup/employee.fbk',mode='wb') + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.local_backup(database='employee.fdb', backup_stream=f, + flags=SrvBackupFlag.IGNORE_CHECKSUMS | SrvBackupFlag.NO_GARBAGE_COLLECT) + f.close() + + ``` + +* `~.ServerDbServices3.restore()` - Performs database restore from logical (GBAK) backup. + + This method is so-called `Async service` that only initiates the restore process. Output + from gbak could be read by one from many methods for [text output from Services](usage-guide.md#text-output-from-services) that + `.Server` provides . + + ```python + from firebird.driver import connect_server, SrvRestoreFlag + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.restore(backup='/backup/employee.fbk', + database='/data/employee.fdb', + flags=SrvRestoreFlag.REPLACE, + stats='TD', verbose=True, page_size=8192) + report = srv.readlines() + + ``` + +* `~.ServerDbServices3.local_restore()` - Performs database restore from logical (GBAK) backup + stored in local byte stream. + + ```python + from firebird.driver import connect_server, SrvRestoreFlag + f = open('/backup/employee.fbk',mode='rb') + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.local_restore(backup_stream=f, database='/data/employee.fdb', + flags=SrvRestoreFlag.REPLACE, page_size=8192) + f.close() + + ``` + +* `~.ServerDbServices3.nbackup()` - Performs physical (NBACKUP) database backup. + + ```python + from firebird.driver import connect_server + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.nbackup(database='employee.fdb', backup='/backup/employee.bkp1', level=1) + + ``` + +* `~.ServerDbServices3.nrestore()` - Performs restore from physical (NBACKUP) database + backup. + + ```python + from firebird.driver import connect_server + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.nrestore(backups=['/backup/employee.bkp0', '/backup/employee.bkp1'], + database='/data/employee.fdb') + + ``` + +* `~.ServerDbServices3.shutdown()` - Database shutdown. + + ```python + from firebird.driver import connect_server, ShutdownMode, ShutdownMethod + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.shutdown(database='employee.fdb', mode=ShutdownMode.SINGLE, + method=ShutdownMethod.FORCED, timeout=10) + + ``` + +* `~.ServerDbServices3.bring_online()` - Bring previously shut down database back online. + + ```python + from firebird.driver import connect_server, OnlineMode + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.bring_online(database='employee.fdb', mode=OnlineMode.MULTI) + + ``` + +* `~.ServerDbServices3.sweep()` - Performs database sweep operation. + + ```python + from firebird.driver import connect_server + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.sweep(database='employee.fdb') + + ``` + +* `~.ServerDbServices3.validate()` - Performs database validation. + + This method is so-called `Async service` that only initiates the validation process. Output + from validation could be read by one from many methods for [text output from Services](usage-guide.md#text-output-from-services) that + `.Server` provides . + + ```python + from firebird.driver import connect_server + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.validate(database='employee.fdb') + report = srv.readlines() + + ``` + +* `~.ServerDbServices3.repair()` - Performs database repair operation. + + ```python + from firebird.driver import connect_server, SrvRepairFlag + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.repair(database='employee.fdb', + flags=SrvRepairFlag.REPAIR | SrvRepairFlag.KILL_SHADOWS) + + ``` + +* `~.ServerDbServices3.get_limbo_transaction_ids()` - Returns list of transactions in limbo. + +* `~.ServerDbServices3.commit_limbo_transaction()` - Resolves limbo transaction with commit. + +* `~.ServerDbServices3.rollback_limbo_transaction()` - Resolves limbo transaction with rollback. + +* `~.ServerDbServices.nfix_database` - Fixup database after filesystem copy. + +* `~.ServerDbServices.set_replica_mode` - Manage replica database. + + +### User maintenance + +!!! important + + Because user maintenance functionality may depend on the version of the Firebird + server, this functionality is made available through a separate class + `.ServerUserServices`. The `.Server.user` property provides access to + instance of `.ServerUserServices` or it's **ancestor** class according to attached + Firebird server version. + +!!! tip + + Since Firebird 2.5 you can use SQL commands (CREATE/ALTER/DROP USER) to manage users in + a security database from a regular database attachment. + + The SQL set of DDL commands for managing user accounts has been further enhanced in Firebird 3, + thus improving the DDL capabilities in a way that exceeds capabilities of user management services. + +* `~.ServerUserServices.get_all()` - Returns information about all users. + +* `~.ServerUserServices.get()` - Returns information about specified users. + +* `~.ServerUserServices.add()` - Add new user. + +* `~.ServerUserServices.update()` - Update user information. + +* `~.ServerUserServices.delete()` - Delete user. + +* `~.ServerUserServices.exists()` - Returns True if user exists. + + +### Trace sessions + +!!! important + + Because trace functionality may depend on the version of the Firebird server, this + functionality is made available through a separate class `.ServerTraceServices`. + The `.Server.trace` property provides access to instance of `.ServerTraceServices` or + its **ancestor** class according to attached Firebird server version. + +* `.ServerTraceServices.start()` - Start new trace session. Requires trace `configuration` and returns `Session ID`. + + This method is so-called `Async service` that only starts the trace session. Output + from trace session could be read by one from many methods for [text output from Services](usage-guide.md#text-output-from-services) + that `.Server` provides . + + ```python + from firebird.driver import connect_server + + trace_config = """database = %[\\/]employee.fdb + { + enabled = true + log_statement_finish = true + print_plan = true + include_filter = %%SELECT%% + exclude_filter = %%RDB$%% + time_threshold = 0 + max_sql_length = 2048 + } + """ + + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + trace_id = srv.trace.start(trace_config,'test_trace_1') + trace_log = [] + # Get first 10 lines of trace output + for i in range(10): + trace_log.append(srv.readline()) + # Stop trace session + # Because trace session blocks the connection, we need another one to stop trace session! + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv_aux: + srv_aux.trace.stop(trace_id) + + ``` + +* `.ServerTraceServices.stop()` - Stop trace session. + +* `.ServerTraceServices.suspend()` - Suspend trace session. + +* `.ServerTraceServices.resume()` - Resume trace session. + +* `.ServerTraceServices.sessions` - Dictionary with active trace sessions. The key is session ID, value is `.TraceSession` instance. + + + +## Logging driver activities + +The firebird-driver supports [context-based logging system](https://firebird-base.readthedocs.io/en/latest/logging/) +provided by [firebird-base](https://firebird-base.rtfd.io) package through use of `~firebird.base.logging.LoggingIdMixin`. + +Classes that use `~firebird.base.logging.LoggingIdMixin`: + +* `.Connection` - Internally used objects have `_logging_id_` set to 'Transaction.Main', + 'Transaction.Query' and 'Cursor.internal'. The log context is not defined. +* `.TransactionManager` - The `_logging_id_` is set to 'Transaction'. The + `~.TransactionManager.log_context()` is the `.Connection`. +* `.DistributedTransactionManager` - The `_logging_id_` is set to 'DTransaction'. The + `~.DistributedTransactionManager.log_context()` is `~firebird.base.types.UNDEFINED`. +* `.Statement` - The `~.Statement.log_context()` is `.Connection`. +* `.BlobReader` - The `~.Statement.log_context()` is the owning object or `~firebird.base.types.UNDEFINED`. +* `.Cursor` - The `~.Cursor.log_context()` is `.Connection`. +* `.Server` - The log context is not defined. + +**Example:** + +```python +import logging +from firebird.base.logging import get_logger, LogLevel +from firebird.driver import connect, driver_config + +# Helper function +def execute(cur: Cursor, cmd: str) -> None: + get_logger(cur).debug(f"Execute [{cmd=}]") + cur.execute(cmd) + +# Basic Python logging configuration +sh = logging.StreamHandler() +sh.setFormatter(logging.Formatter('%(levelname)-10s: [%(agent)s][%(context)s] %(message)s')) +logger = logging.getLogger() +logger.addHandler(sh) +logger.setLevel(LogLevel.DEBUG) + +# Firebird driver configuration +srv_cfg = """[local] +host = localhost +user = SYSDBA +password = masterkey +""" +driver_config.register_server('local', srv_cfg) +db_cfg = """[employee] +server = local +database = employee.fdb +protocol = inet +""" +driver_config.register_database('employee', db_cfg) + +print("Default logging ids") +with connect('employee') as con: + con_log = get_logger(con) + con_log.info('Start') + cur1 = con.cursor() + cur2 = con.cursor() + execute(cur1, 'select * from country') + execute(cur2, 'select * from project') + con_log.info('Stop') + +print("Custom logging ids") +with connect('employee') as con: + con._logging_id_ = 'employee-1' + con_log = get_logger(con) + con_log.info('Start') + cur1 = con.cursor() + cur1._logging_id_ = 'cursor-1' + cur2 = con.cursor() + cur2._logging_id_ = 'cursor-2' + execute(cur1, 'select * from country') + execute(cur2, 'select * from project') + con_log.info('Stop') + +``` + +Output: + +```text +Default logging ids +INFO : [Connection][UNDEFINED] Start +DEBUG : [Cursor][Connection] Execute [cmd='select * from country'] +DEBUG : [Cursor][Connection] Execute [cmd='select * from project'] +INFO : [Connection][UNDEFINED] Stop +Custom logging ids +INFO : [employee-1][UNDEFINED] Start +DEBUG : [cursor-1][employee-1] Execute [cmd='select * from country'] +DEBUG : [cursor-2][employee-1] Execute [cmd='select * from project'] +INFO : [employee-1][UNDEFINED] Stop + +``` +You can also trace the driver activities using [trace/audit for class instances](https://firebird-base.readthedocs.io/en/latest/trace/) +provided by [firebird-base](https://firebird-base.rtfd.io) package. + +**Example:** + +```python +import logging +from firebird.base.logging import get_logger, LogLevel +from firebird.base.trace import trace_manager, add_trace, trace_object, traced, TraceFlag +from firebird.driver import connect, driver_config +from firebird.driver.core import TransactionManager + +# Helper function +def execute(cur: Cursor, cmd: str) -> None: + cur.execute(cmd) + +# Basic Python logging configuration +sh = logging.StreamHandler() +sh.setFormatter(logging.Formatter('%(levelname)-10s: [%(agent)s][%(context)s] %(message)s')) +logger = logging.getLogger() +logger.addHandler(sh) +logger.setLevel(LogLevel.DEBUG) + +# Firebird driver configuration +srv_cfg = """[local] +host = localhost +user = SYSDBA +password = masterkey +""" +driver_config.register_server('local', srv_cfg) +db_cfg = """[employee] +server = local +database = employee.fdb +protocol = inet +""" +driver_config.register_database('employee', db_cfg) + +# Trace configuration +# First: register classes and methods that could be traced +trace_manager.register(Connection) +add_trace(Connection, 'close', traced) +trace_manager.register(TransactionManager) +add_trace(TransactionManager, 'begin', traced) +add_trace(TransactionManager, 'commit', traced) +add_trace(TransactionManager, 'rollback', traced) +trace_manager.register(Cursor) +add_trace(Cursor, 'execute', traced) +add_trace(Cursor, 'close', traced) +# Activate trace/audit +trace_manager.trace |= (TraceFlag.ACTIVE | TraceFlag.BEFORE | TraceFlag.AFTER | TraceFlag.FAIL) + +# Traced code +with connect('employee') as con: + trace_object(con) + trace_object(con.main_transaction) + con._logging_id_ = 'employee-1' + cur1 = con.cursor() + trace_object(cur1) + cur1._logging_id_ = 'cursor-1' + cur2 = con.cursor() + trace_object(cur2) + cur2._logging_id_ = 'cursor-2' + execute(cur1, 'select * from country') + execute(cur2, 'select * from project') + con.commit() + +``` + +Sample output: + +```text +DEBUG : [cursor-1][employee-1] >>> execute(operation='select * from country', parameters=None) +DEBUG : [Transaction.Main][employee-1] >>> begin(tpb=None) +DEBUG : [Transaction.Main][employee-1] <<< begin[0.00672] +DEBUG : [cursor-1][employee-1] >>> close() +DEBUG : [cursor-1][employee-1] <<< close[0.00004] +DEBUG : [cursor-1][employee-1] <<< execute[0.01119] Result: cursor-1 +DEBUG : [cursor-2][employee-1] >>> execute(operation='select * from project', parameters=None) +DEBUG : [cursor-2][employee-1] >>> close() +DEBUG : [cursor-2][employee-1] <<< close[0.00002] +DEBUG : [cursor-2][employee-1] <<< execute[0.00352] Result: cursor-2 +DEBUG : [Transaction.Main][employee-1] >>> commit(retaining=False) +DEBUG : [cursor-1][employee-1] >>> close() +DEBUG : [cursor-1][employee-1] <<< close[0.00017] +DEBUG : [cursor-2][employee-1] >>> close() +DEBUG : [cursor-2][employee-1] <<< close[0.00012] +DEBUG : [Transaction.Main][employee-1] <<< commit[0.00225] +DEBUG : [employee-1][UNDEFINED] >>> close() +DEBUG : [employee-1][UNDEFINED] <<< close[0.00764] + + +``` +If you will remove the `con.commit()` from the example above, the output will change to: + +```text +DEBUG : [cursor-1][employee-1] >>> execute(operation='select * from country', parameters=None) +DEBUG : [Transaction.Main][employee-1] >>> begin(tpb=None) +DEBUG : [Transaction.Main][employee-1] <<< begin[0.00338] +DEBUG : [cursor-1][employee-1] >>> close() +DEBUG : [cursor-1][employee-1] <<< close[0.00003] +DEBUG : [cursor-1][employee-1] <<< execute[0.00730] Result: cursor-1 +DEBUG : [cursor-2][employee-1] >>> execute(operation='select * from project', parameters=None) +DEBUG : [cursor-2][employee-1] >>> close() +DEBUG : [cursor-2][employee-1] <<< close[0.00003] +DEBUG : [cursor-2][employee-1] <<< execute[0.00345] Result: cursor-2 +DEBUG : [employee-1][UNDEFINED] >>> close() +DEBUG : [Transaction.Main][employee-1] >>> rollback(retaining=False, savepoint=None) +DEBUG : [cursor-1][employee-1] >>> close() +DEBUG : [cursor-1][employee-1] <<< close[0.00016] +DEBUG : [cursor-2][employee-1] >>> close() +DEBUG : [cursor-2][employee-1] <<< close[0.00014] +DEBUG : [Transaction.Main][employee-1] <<< rollback[0.00171] +DEBUG : [employee-1][UNDEFINED] <<< close[0.01001] + + +``` + + + + +## Driver hooks + +The firebird-driver uses [hook manager](https://firebird-base.readthedocs.io/en/latest/hooks/) from [firebird-base](https://firebird-base.rtfd.io) package +to provide internal notification mechanism that allows installation of custom hooks into +certain driver tasks. + +Driver hooks are divided into several types exposed as enums in `firebird.driver.hooks` module. + +### APIHook + +`.APIHook.LOADED` - This hook is invoked once when instance of `.FirebirdAPI` is created. +It could be used for additional initialization tasks that require Firebird API, or to manipulate +the FirebirdAPI instance itself before its use. + +Hook routine must have signature: `hook_func(api: FirebirdAPI) -> None`. Any value returned +by hook is ignored. + +### ConnectionHook + +* `.ConnectionHook.ATTACH_REQUEST` + + This hook is invoked after all parameters are preprocessed and before `.Connection` is created. + + Hook routine must have signature: `hook_func(dsn: str, dpb: bytes) -> Optional[Connection]` + where `dpb` is Database Parameter Buffer that would be used to create the attachment to the + database defined by `dsn`. It may return `.Connection` (or subclass) instance or `None`. + + First instance returned by any hook of this type will become the return value of caller function + and other hooks of the same type are not invoked. + +* `.ConnectionHook.ATTACHED` + + This hook is invoked just before `.Connection` (or subclass) instance is returned to the client + application. + + Hook routine must have signature: `hook_func(con: Connection) -> None`. + +* `.ConnectionHook.DETACH_REQUEST` + + This hook is invoked before connection is closed. + + Hook must have signature: `hook_func(con: Connection) -> None`. + + If any hook function returns True, connection is not closed. + +* `.ConnectionHook.CLOSED` + + This hook is invoked after connection is closed. + + Hook routine must have signature: `hook_func(con: Connection) -> None`. + +* `.ConnectionHook.DROPPED` + + This hook is invoked after database is dropped (and connection is closed). + + Hook routine must have signature: `hook_func(con: Connection) -> None`. + +### ServerHook + +* `.ServerHook.ATTACHED` + + This hook is invoked before `.Server` instance is returned. + + Hook routine must have signature: `hook_func(srv: Server) -> None`. + + + +[DDL]: http://en.wikipedia.org/wiki/Data_Definition_Language +[DML]: http://en.wikipedia.org/wiki/Data_Manipulation_Language +[Firebird SAVEPOINTs]: http://www.firebirdsql.org/refdocs/langrefupd15-savepoint.html +[Firebird Book]: https://www.ibphoenix.com/products/books/firebird_book +[busy-wait]: http://www.catb.org/jargon/html/B/busy-wait.html +[Visitor Pattern]: http://en.wikipedia.org/wiki/Visitor_pattern +[setuptools]: https://pypi.org/project/setuptools/ +[PYPI]: https://pypi.org/ +[ctypes]: http://docs.python.org/library/ctypes.html +[pip]: https://pypi.org/project/pip/ +[firebird-base]: https://firebird-base.rtfd.io diff --git a/docs/getting-started.txt b/docs/getting-started.txt deleted file mode 100644 index eccd98d..0000000 --- a/docs/getting-started.txt +++ /dev/null @@ -1,329 +0,0 @@ - -############### -Getting Started -############### - -Installation -************ - -Firebird-driver is written as pure-Python module (requires Python 3.8+) on top of -Firebird client library (fbclient.so/dll) using ctypes_. Driver supports Firebird version -3.0 and higher. - -Firebird-driver is distributed as `setuptools`_ package and the preferred installation -method is via pip_ tool. - -Installation from PYPI_ -======================= - -Run pip:: - - $ pip install firebird-driver - -Quick-start Guide -***************** - -This brief tutorial aims to get the reader started by demonstrating elementary usage of -Firebird-driver. It is not a comprehensive Python Database API tutorial, nor is it -comprehensive in its coverage of anything else. - -The numerous advanced features of Firebird-driver are covered in another section of this -documentation, which is not in a tutorial format, though it is replete with examples. - -Driver configuration -==================== - -The driver uses configuration built on top of `configuration system ` -provided by `firebird-base`_ package. In addition to global settings, the configuration -also includes the definition of connection parameters to Firebird servers and databases. - -The default configuration connects to embedded server using direct/local connection method. -To access remote servers and databases (or local ones through remote protocols), it's -necessary to adjust default configuration, or `register` them in configuration manager. - -You can manipulate the configuration objects directly, or load configuration from files or -strings (in `.ini-style` `ConfigParser` format). - -Connecting to a Database -======================== - -**Example 1:** - -A simple database connection is typically established with code such as this: - -.. sourcecode:: python - - from firebird.driver import connect - - # Attach to 'employee' database/alias using embedded server connection - con = connect('employee', user='sysdba', password='masterkey') - - # Attach to 'employee' database/alias using local server connection - from firebird.driver import driver_config - driver_config.server_defaults.host.value = 'localhost' - con = connect('employee', user='sysdba', password='masterkey') - - # Set 'user' and 'password' via configuration - driver_config.server_defaults.user.value = 'SYSDBA' - driver_config.server_defaults.password.value = 'masterkey' - con = connect('employee') - -**Example 2:** - -A database connection typically uses specific configuration, and is established with code -such as this: - -.. sourcecode:: python - - from firebird.driver import connect, driver_config - - # Register Firebird server - srv_cfg = """[local] - host = localhost - user = SYSDBA - password = masterkey - """ - driver_config.register_server('local', srv_cfg) - - # Register database - db_cfg = """[employee] - server = local - database = employee.fdb - protocol = inet - charset = utf8 - """ - driver_config.register_database('employee', db_cfg) - - # Attach to 'employee' database - con = connect('employee') - -.. note:: - - Some parameters like 'user' and 'password' could be overridden with keyword parameters. - Few parameters like 'crypt_callback' or 'no_db_triggers' could be specified **ONLY** - as keyword arguments. - -Creating a Database -=================== - -A database is created using `~firebird.driver.core.create_database()` function. -Like `~firebird.driver.core.connect()`, this function uses configuration for specification of -database parameters like page size, sweep interval etc. - -Executing SQL Statements -======================== - -For this section, suppose we have a table defined and populated by the following SQL code: - -.. sourcecode:: sql - - create table languages - ( - name varchar(20), - year_released integer - ); - - insert into languages (name, year_released) values ('C', 1972); - insert into languages (name, year_released) values ('Python', 1991); - -**Example 1** - -This example shows the *simplest* way to print the entire contents of -the `languages` table: - -.. sourcecode:: python - - from firebird.driver import connect - - con = connect('test.fdb', user='sysdba', password='masterkey') - - # Create a Cursor object that operates in the context of Connection con: - cur = con.cursor() - - # Execute the SELECT statement: - cur.execute("select * from languages order by year_released") - - # Retrieve all rows as a sequence and print that sequence: - print(cur.fetchall()) - -Sample output: - -.. sourcecode:: python - - [('C', 1972), ('Python', 1991)] - -**Example 2** - -Here's another trivial example that demonstrates various ways of fetching a single row at a time from a `SELECT`-cursor: - -.. sourcecode:: python - - from firebird.driver import connect - - con = connect('test.fdb', user='sysdba', password='masterkey') - - cur = con.cursor() - SELECT = "select name, year_released from languages order by year_released" - - # 1. Iterate over the rows available from the cursor, unpacking the - # resulting sequences to yield their elements (name, year_released): - cur.execute(SELECT) - for (name, year_released) in cur: - print(f'{name} has been publicly available since {year_released}.') - - # 2. Equivalently: - cur.execute(SELECT) - for row in cur: - print(f'{row[0]} has been publicly available since {row[1]}.') - -Sample output: - -.. sourcecode:: python - - C has been publicly available since 1972. - Python has been publicly available since 1991. - C has been publicly available since 1972. - Python has been publicly available since 1991. - C has been publicly available since 1972. - Python has been publicly available since 1991. - -**Example 3** - -The following program is a simplistic table printer (applied in this example to `languages`): - -.. sourcecode:: python - - from firebird.driver import connect, DESCRIPTION_NAME, DESCRIPTION_DISPLAY_SIZE - - TABLE_NAME = 'languages' - SELECT = f'select * from {TABLE_NAME} order by year_released' - - con = connect('test.fdb', user='sysdba', password='masterkey') - - cur = con.cursor() - cur.execute(SELECT) - - # Print a header. - for fieldDesc in cur.description: - print(fieldDesc[DESCRIPTION_NAME].ljust(fieldDesc[DESCRIPTION_DISPLAY_SIZE]), end='') - print() # Finish the header with a newline. - print('-' * 78) - - # For each row, print the value of each field left-justified within - # the maximum possible width of that field. - fieldIndices = range(len(cur.description)) - for row in cur: - for fieldIndex in fieldIndices: - fieldValue = str(row[fieldIndex]) - fieldMaxWidth = cur.description[fieldIndex][DESCRIPTION_DISPLAY_SIZE] - - print(fieldValue.ljust(fieldMaxWidth), end='') - - print() # Finish the row with a newline. - - -Sample output: - -.. sourcecode:: python - - NAME YEAR_RELEASED - ------------------------------------------------------------------------------ - C 1972 - Python 1991 - - -**Example 4** - -Let's insert more languages: - -.. sourcecode:: python - - from firebird.driver import connect - - con = connect('test.fdb', user='sysdba', password='masterkey') - - cur = con.cursor() - - newLanguages = [ - ('Lisp', 1958), - ('Dylan', 1995), - ] - - cur.executemany("insert into languages (name, year_released) values (?, ?)", - newLanguages - ) - - # The changes will not be saved unless the transaction is committed explicitly: - con.commit() - - -Note the use of a *parameterized* SQL statement above. When dealing with repetitive -statements, this is much faster and less error-prone than assembling each SQL statement -manually. (You can read more about parameterized SQL statements in the section on -:ref:`Prepared Statements `.) - -After running Example 4, the table printer from Example 3 would print: - -.. sourcecode:: python - - NAME YEAR_RELEASED - ------------------------------------------------------------------------------ - Lisp 1958 - C 1972 - Python 1991 - Dylan 1995 - - -Calling Stored Procedures -========================= - -Firebird supports stored procedures written in a proprietary procedural SQL language. -Firebird stored procedures can have *input* parameters and/or *output* parameters. Some -databases support *input/output* parameters, where the same parameter is used for both -input and output; Firebird does not support this. - -It is important to distinguish between procedures that *return a result set* and procedures -that *populate and return their output parameters exactly once*. Conceptually, the latter -"return their output parameters" like a Python function, whereas the former "yield result -rows" like a Python generator. - -Firebird's *server-side* procedural SQL syntax makes no such distinction, but *client-side* -SQL code (and C API code) must. A result set is retrieved from a stored procedure by -`SELECT`-ing from the procedure, whereas output parameters are retrieved with an -`EXECUTE PROCEDURE` statement. - -To *retrieve a result set* from a stored procedure with Firebird-driver, use code such as this: - -.. sourcecode:: python - - cur.execute("select output1, output2 from the_proc(?, ?)", (input1, input2)) - - # Ordinary fetch code here, such as: - for row in cur: - ... # process row - - con.commit() # If the procedure had any side effects, commit them. - - -To *execute* a stored procedure and *access its output parameters*, use code such as this: - -.. sourcecode:: python - - cur.callproc("the_proc", (input1, input2)) - - # If there are output parameters, retrieve them as though they were the - # first row of a result set. For example: - outputParams = cur.fetchone() - - con.commit() # If the procedure had any side effects, commit them. - - -This latter is not very elegant; it would be preferable to access the procedure's output -parameters as the return value of `Cursor.callproc()`. The Python DB API specification -requires the current behavior, however. - -.. _setuptools: https://pypi.org/project/setuptools/ -.. _PYPI: https://pypi.org/ -.. _ctypes: http://docs.python.org/library/ctypes.html -.. _pip: https://pypi.org/project/pip/ -.. _firebird-base: https://firebird-base.rtfd.io diff --git a/docs/index.txt b/docs/index.txt deleted file mode 100644 index 3a5e65f..0000000 --- a/docs/index.txt +++ /dev/null @@ -1,58 +0,0 @@ - -############################## -The Python driver for Firebird -############################## - -The `firebird-driver` package provides official `Python Database API 2.0`_-compliant driver -for the open source relational database `Firebird`_ ®. In addition to the minimal feature -set of the standard Python DB API, this driver also exposes the new (interface-based) client -API introduced in Firebird 3, and number of additional extensions and enhancements for -convenient use of Firebird RDBMS. - -This documentation set is not a tutorial on SQL or Firebird; rather, it is a topical -presentation of driver's feature set, with example code to demonstrate basic usage patterns. -For detailed information about Firebird features, see the -`Firebird documentation `__, and especially -the excellent `The Firebird Book `__ -written by Helen Borrie and published by IBPhoenix_. - -.. seealso:: `firebird-lib`_ package for optional extensions to this driver. - -.. note:: Requires Python 3.11+ - -.. tip:: You can download docset for Dash_ (MacOS) or Zeal_ (Windows / Linux) documentation - readers from releases_ at github. - -Content -******* - -.. toctree:: - :maxdepth: 2 - :caption: Contents: - - getting-started - usage-guide - python-db-api-compliance - reference - changelog - license - -Driver development is sponsored by IBPhoenix_. - -Indices and tables -****************** - -* :ref:`genindex` -* :ref:`modindex` - -.. _IBPhoenix: http://www.ibphoenix.com -.. _Python: http://python.org -.. _Python Database API 2.0: http://www.python.org/dev/peps/pep-0249/ -.. _Firebird: http://www.firebirdsql.org -.. _under: http://www.firebirdsql.org/en/devel-python-driver/ -.. _Firebird Project: http://www.firebirdsql.org -.. _IBPhoenix: http://www.ibphoenix.com -.. _firebird-lib: https://pypi.org/project/firebird-lib/ -.. _releases: https://github.com/FirebirdSQL/python3-driver/releases -.. _Dash: https://kapeli.com/dash -.. _Zeal: https://zealdocs.org/ diff --git a/docs/license.txt b/docs/license.txt deleted file mode 100644 index 935e89d..0000000 --- a/docs/license.txt +++ /dev/null @@ -1,6 +0,0 @@ -####### -License -####### - -.. include:: ../LICENSE - diff --git a/docs/make-docset b/docs/make-docset deleted file mode 100755 index c059d5f..0000000 --- a/docs/make-docset +++ /dev/null @@ -1,2 +0,0 @@ -doc2dash -u https://firebird-driver.readthedocs.io/en/latest/ -f -i ./_static/fb-favicon.png -n firebird-driver ./_build/html/ -tar --exclude='.DS_Store' -cvzf ../dist/firebird-driver-docset.tgz firebird-driver.docset diff --git a/docs/make.bat b/docs/make.bat deleted file mode 100644 index 2119f51..0000000 --- a/docs/make.bat +++ /dev/null @@ -1,35 +0,0 @@ -@ECHO OFF - -pushd %~dp0 - -REM Command file for Sphinx documentation - -if "%SPHINXBUILD%" == "" ( - set SPHINXBUILD=sphinx-build -) -set SOURCEDIR=. -set BUILDDIR=_build - -if "%1" == "" goto help - -%SPHINXBUILD% >NUL 2>NUL -if errorlevel 9009 ( - echo. - echo.The 'sphinx-build' command was not found. Make sure you have Sphinx - echo.installed, then set the SPHINXBUILD environment variable to point - echo.to the full path of the 'sphinx-build' executable. Alternatively you - echo.may add the Sphinx directory to PATH. - echo. - echo.If you don't have Sphinx installed, grab it from - echo.http://sphinx-doc.org/ - exit /b 1 -) - -%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% -goto end - -:help -%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% - -:end -popd diff --git a/docs/ref-core.txt b/docs/ref-core.txt deleted file mode 100644 index 42fd282..0000000 --- a/docs/ref-core.txt +++ /dev/null @@ -1,101 +0,0 @@ -.. module:: firebird.driver.core - :synopsis: Main Firebird driver code - -==================== -firebird.driver.core -==================== - -This is the main code module of the Firebird driver. - -Constants and variables -======================= - -C integer limit constants -------------------------- - -.. hlist:: - :columns: 4 - - - SHRT_MIN - - SHRT_MAX - - USHRT_MAX - - INT_MIN - - INT_MAX - - UINT_MAX - - LONG_MIN - - LONG_MAX - -Translation dictionaries ------------------------- - -.. autodata:: CHARSET_MAP - :no-value: - -Other constants and variables ------------------------------ - -.. autodata:: MAX_BLOB_SEGMENT_SIZE - -.. autodata:: FS_ENCODING - :no-value: - -.. autodata:: _master - :no-value: - -.. autodata:: _util - :no-value: - -.. autodata:: TIMEOUT - :no-value: - -Context managers -================ - -.. autofunction:: transaction -.. autofunction:: temp_database - -Functions -========= - -.. autofunction:: connect -.. autofunction:: create_database -.. autofunction:: connect_server -.. autofunction:: tpb - -Managers for parameter buffers -============================== - -.. autoclass:: TPB -.. autoclass:: DPB -.. autoclass:: SPB_ATTACH -.. autoclass:: Buffer -.. autoclass:: CBuffer - -Classes -======= - -.. autoclass:: Connection -.. autoclass:: TransactionManager -.. autoclass:: DistributedTransactionManager -.. autoclass:: Statement -.. autoclass:: Cursor -.. autoclass:: Server -.. autoclass:: ServerServiceProvider -.. autoclass:: ServerDbServices3 -.. autoclass:: ServerDbServices -.. autoclass:: ServerUserServices -.. autoclass:: ServerTraceServices -.. autoclass:: InfoProvider -.. autoclass:: DatabaseInfoProvider3 -.. autoclass:: DatabaseInfoProvider -.. autoclass:: TransactionInfoProvider3 -.. autoclass:: TransactionInfoProvider -.. autoclass:: StatementInfoProvider3 -.. autoclass:: StatementInfoProvider -.. autoclass:: ServerInfoProvider -.. autoclass:: EventCollector -.. autoclass:: EventBlock -.. autoclass:: BlobReader -.. autoclass:: EngineVersionProvider - - diff --git a/docs/ref-fbapi.txt b/docs/ref-fbapi.txt deleted file mode 100644 index da88813..0000000 --- a/docs/ref-fbapi.txt +++ /dev/null @@ -1,451 +0,0 @@ -.. module:: firebird.driver.fbapi - :synopsis: Python ctypes interface to Firebird client library - -===================== -firebird.driver.fbapi -===================== - -This module contains low-level :ref:`ctypes ` interface to -Firebird client library (`fbclient.so/dll`). - -Constants -========= - -Type codes ----------- - -.. hlist:: - :columns: 6 - - - SQL_TEXT - - SQL_VARYING - - SQL_SHORT - - SQL_LONG - - SQL_FLOAT - - SQL_DOUBLE - - SQL_D_FLOAT - - SQL_TIMESTAMP - - SQL_BLOB - - SQL_ARRAY - - SQL_QUAD - - SQL_TYPE_TIME - - SQL_TYPE_DATE - - SQL_INT64 - - SQL_BOOLEAN - - SQL_NULL - - SUBTYPE_NUMERIC - - SUBTYPE_DECIMAL - -Internal type codes (for example used by ARRAY descriptor) ----------------------------------------------------------- - -.. hlist:: - :columns: 6 - - - blr_text - - blr_text2 - - blr_short - - blr_long - - blr_quad - - blr_float - - blr_double - - blr_d_float - - blr_timestamp - - blr_varying - - blr_varying2 - - blr_blob - - blr_cstring - - blr_cstring2 - - blr_blob_id - - blr_sql_date - - blr_sql_time - - blr_int64 - - blr_blob2 - - blr_domain_name - - blr_domain_name2 - - blr_not_nullable - - blr_column_name - - blr_column_name2 - - blr_bool - - blr_dec64 - - blr_dec128 - - blr_dec_fixed - - blr_sql_time_tz - - blr_timestamp_tz - - blr_ex_time_tz - - blr_ex_timestamp_tz - -Types -===== - -.. autoclass:: Int - :no-show-inheritance: - -.. autoclass:: IntPtr - :no-show-inheritance: - -.. autoclass:: Int64 - :no-show-inheritance: - -.. autoclass:: Int64Ptr - :no-show-inheritance: - -.. autoclass:: QWord - :no-show-inheritance: - -.. autoclass:: STRING - :no-show-inheritance: - -.. autoclass:: ISC_LONG - :no-show-inheritance: - -.. autoclass:: ISC_LONG_PTR - :no-show-inheritance: - -.. autoclass:: ISC_ULONG - :no-show-inheritance: - -.. autoclass:: ISC_SHORT - :no-show-inheritance: - -.. autoclass:: ISC_USHORT - :no-show-inheritance: - -.. autoclass:: ISC_UCHAR - :no-show-inheritance: - -.. autoclass:: ISC_INT64 - :no-show-inheritance: - -.. autoclass:: ISC_UINT64 - :no-show-inheritance: - -.. autoclass:: ISC_DATE - :no-show-inheritance: - -.. autoclass:: ISC_TIME - :no-show-inheritance: - -.. autoclass:: FB_DEC16 - :no-show-inheritance: - -.. autoclass:: FB_DEC16Ptr - :no-show-inheritance: - -.. autoclass:: FB_DEC34 - :no-show-inheritance: - -.. autoclass:: FB_DEC34Ptr - :no-show-inheritance: - -.. autoclass:: FB_I128 - :no-show-inheritance: - -.. autoclass:: FB_I128Ptr - :no-show-inheritance: - -.. autoclass:: ISC_QUAD - :no-show-inheritance: - -.. autoclass:: ISC_QUAD_PTR - :no-show-inheritance: - -.. autoclass:: FB_API_HANDLE - :no-show-inheritance: - -.. autoclass:: FB_API_HANDLE_PTR - :no-show-inheritance: - -.. autoclass:: ISC_STATUS - :no-show-inheritance: - -.. autoclass:: ISC_STATUS_PTR - :no-show-inheritance: - -.. autoclass:: ISC_STATUS_ARRAY - :no-show-inheritance: - -.. autoclass:: ISC_STATUS_ARRAY_PTR - :no-show-inheritance: - -.. autoclass:: ISC_ARRAY_BOUND - :no-show-inheritance: - -.. autoclass:: ISC_ARRAY_DESC - :no-show-inheritance: - -.. autoclass:: ISC_ARRAY_DESC_PTR - :no-show-inheritance: - -.. autoclass:: RESULT_VECTOR - :no-show-inheritance: - -.. autoclass:: ISC_TIME_TZ - :no-show-inheritance: - -.. autoclass:: ISC_TIME_TZ_EX - :no-show-inheritance: - -.. autoclass:: ISC_TIMESTAMP - :no-show-inheritance: - -.. autoclass:: ISC_TIMESTAMP_TZ - :no-show-inheritance: - -.. autoclass:: ISC_TIMESTAMP_TZ_EX - :no-show-inheritance: - -.. autoclass:: TraceCounts - :no-show-inheritance: - -.. autoclass:: PerformanceInfo - :no-show-inheritance: - -Variables -========= - -.. autodata:: err_encoding - :no-value: - -Functions -========= - -.. autofunction:: has_api -.. autofunction:: load_api -.. autofunction:: get_api - -Classes -======= - -.. autoclass:: FirebirdAPI - -Firebird API Interface definitions -================================== - -.. autoclass:: IVersioned_VTable - :no-show-inheritance: - -.. autoclass:: IVersioned_struct - :no-show-inheritance: - -.. autoclass:: IReferenceCounted_VTable - :no-show-inheritance: - -.. autoclass:: IReferenceCounted_struct - :no-show-inheritance: - -.. autoclass:: IDisposable_VTable - :no-show-inheritance: - -.. autoclass:: IDisposable_struct - :no-show-inheritance: - -.. autoclass:: IStatus_VTable - :no-show-inheritance: - -.. autoclass:: IStatus_struct - :no-show-inheritance: - -.. autoclass:: IMaster_VTable - :no-show-inheritance: - -.. autoclass:: IMaster_struct - :no-show-inheritance: - -.. autoclass:: IPluginBase_VTable - :no-show-inheritance: - -.. autoclass:: IPluginBase_struct - :no-show-inheritance: - -.. autoclass:: IPluginSet_VTable - :no-show-inheritance: - -.. autoclass:: IPluginSet_struct - :no-show-inheritance: - -.. autoclass:: IConfigEntry_VTable - :no-show-inheritance: - -.. autoclass:: IConfigEntry_struct - :no-show-inheritance: - -.. autoclass:: IConfig_VTable - :no-show-inheritance: - -.. autoclass:: IConfig_struct - :no-show-inheritance: - -.. autoclass:: IFirebirdConf_VTable - :no-show-inheritance: - -.. autoclass:: IFirebirdConf_struct - :no-show-inheritance: - -.. autoclass:: IPluginManager_VTable - :no-show-inheritance: - -.. autoclass:: IPluginManager_struct - :no-show-inheritance: - -.. autoclass:: IConfigManager_VTable - :no-show-inheritance: - -.. autoclass:: IConfigManager_struct - :no-show-inheritance: - -.. autoclass:: IEventCallback_VTable - :no-show-inheritance: - -.. autoclass:: IEventCallback_struct - :no-show-inheritance: - -.. autoclass:: IBlob_VTable - :no-show-inheritance: - -.. autoclass:: IBlob_struct - :no-show-inheritance: - -.. autoclass:: ITransaction_VTable - :no-show-inheritance: - -.. autoclass:: ITransaction_struct - :no-show-inheritance: - -.. autoclass:: IMessageMetadata_VTable - :no-show-inheritance: - -.. autoclass:: IMessageMetadata_struct - :no-show-inheritance: - -.. autoclass:: IMetadataBuilder_VTable - :no-show-inheritance: - -.. autoclass:: IMetadataBuilder_struct - :no-show-inheritance: - -.. autoclass:: IResultSet_VTable - :no-show-inheritance: - -.. autoclass:: IResultSet_struct - :no-show-inheritance: - -.. autoclass:: IStatement_VTable - :no-show-inheritance: - -.. autoclass:: IStatement_struct - :no-show-inheritance: - -.. autoclass:: IBatch_VTable - :no-show-inheritance: - -.. autoclass:: IBatch_struct - :no-show-inheritance: - -.. autoclass:: IBatchCompletionState_VTable - :no-show-inheritance: - -.. autoclass:: IBatchCompletionState_struct - :no-show-inheritance: - -.. autoclass:: IRequest_VTable - :no-show-inheritance: - -.. autoclass:: IRequest_struct - :no-show-inheritance: - -.. autoclass:: IEvents_VTable - :no-show-inheritance: - -.. autoclass:: IEvents_struct - :no-show-inheritance: - -.. autoclass:: IAttachment_VTable - :no-show-inheritance: - -.. autoclass:: IAttachment_struct - :no-show-inheritance: - -.. autoclass:: IService_VTable - :no-show-inheritance: - -.. autoclass:: IService_struct - :no-show-inheritance: - -.. autoclass:: IProvider_VTable - :no-show-inheritance: - -.. autoclass:: IProvider_struct - :no-show-inheritance: - -.. autoclass:: IDtcStart_VTable - :no-show-inheritance: - -.. autoclass:: IDtcStart_struct - :no-show-inheritance: - -.. autoclass:: IDtc_VTable - :no-show-inheritance: - -.. autoclass:: IDtc_struct - :no-show-inheritance: - -.. autoclass:: ICryptKeyCallback_VTable - :no-show-inheritance: - -.. autoclass:: ICryptKeyCallback_struct - :no-show-inheritance: - -.. autoclass:: ITimer_VTable - :no-show-inheritance: - -.. autoclass:: ITimer_struct - :no-show-inheritance: - -.. autoclass:: ITimerControl_VTable - :no-show-inheritance: - -.. autoclass:: ITimerControl_struct - :no-show-inheritance: - -.. autoclass:: IVersionCallback_VTable - :no-show-inheritance: - -.. autoclass:: IVersionCallback_struct - :no-show-inheritance: - -.. autoclass:: IUtil_VTable - :no-show-inheritance: - -.. autoclass:: IUtil_struct - :no-show-inheritance: - -.. autoclass:: IOffsetsCallback_VTable - :no-show-inheritance: - -.. autoclass:: IOffsetsCallback_struct - :no-show-inheritance: - -.. autoclass:: IXpbBuilder_VTable - :no-show-inheritance: - -.. autoclass:: IXpbBuilder_struct - :no-show-inheritance: - -.. autoclass:: IDecFloat16_VTable - :no-show-inheritance: - -.. autoclass:: IDecFloat16_struct - :no-show-inheritance: - -.. autoclass:: IDecFloat34_VTable - :no-show-inheritance: - -.. autoclass:: IDecFloat34_struct - :no-show-inheritance: - -.. autoclass:: IInt128_VTable - :no-show-inheritance: - -.. autoclass:: IInt128_struct - :no-show-inheritance: diff --git a/docs/ref-intf.txt b/docs/ref-intf.txt deleted file mode 100644 index 7386e69..0000000 --- a/docs/ref-intf.txt +++ /dev/null @@ -1,152 +0,0 @@ -.. module:: firebird.driver.interfaces - :synopsis: Interface wrappers for Firebird new API - -========================== -firebird.driver.interfaces -========================== - -This module contains interface wrappers for Firebird new API. - -.. important:: - - 1. Firebird OO API interfaces use inheritance, i.e. they could be inherited from other - interface. In fact, all interfaces returned by Firebird are inherited from `IVersioned` - interface. - - 2. Firebird OO API interfaces are versioned. Any addition to particular interface - increases its version number. Application developers are responsible to check the - version of returned interface to verify that it supports methods they want to use. - - If you want to use Firebird OO API interfaces directly in you application, read next - section very carefuly. - -In Python driver, interfaces are represented as instances of interface wrapper classes -that expose the methods provided by particular Firebird interface version. The wrapper -class hierarchy thus represent not only inheritabce between Firebird interfaces, but also -between versions of particular Firebird interface. - -Because all interfaces returned by Firebird are inherited from `IVersioned` interface, -all wrapper classes have `VERSION` class attribute that contain version number of wrapped -interface. - -Each Firebird interface has it's "canonical" Python wrapper with coresponding name. For -example interface `IService` has wrapper class `.iService`. However, if there are multiple -public versions of Firebird interface, there are multiple wrapper classes for each published -interface version (interim, non-public versions used during Firebird development are skipped). -These wrapper classes have names based on their canonical name with suffix that represent -the interface version they wrap. It means that canonical wrapper **always** represents -the highest interface version. - -Whenever Firebird interface is returned from Firebird OO API call, it's wrapped to its -Python wrapper class according to interface type and version. The Python driver ensures -that correct wrapper class is used according to returned interface version. - -However, this architecture has several important consequences: - -1. The interface wrapper classes may change between driver releases as new interface versions - are introduced. For example, driver versions up to 1.5.2 had only canonical `.iService` - (version 3), but in version 1.6.0 it was renamed to `.iService_v3`, new wrappers - `.iService_v4` and (new canonical) `.iService` (version 5) were added. -2. Instead using `isinstance` to check interface versions, you should always use - `VERSION` attribute on wrapper class instance. - - -Metaclasses -=========== - -.. autoclass:: iVersionedMeta - -Firebird API Interface wrappers -=============================== - -Base interfaces ---------------- -.. autoclass:: iVersioned -.. autoclass:: iReferenceCounted -.. autoclass:: iDisposable -.. autoclass:: iStatus -.. autoclass:: iPluginBase -.. autoclass:: iMaster - -Configuration -------------- -.. autoclass:: iConfigEntry -.. autoclass:: iConfig -.. autoclass:: iFirebirdConf_v3 -.. autoclass:: iFirebirdConf -.. autoclass:: iConfigManager_v2 -.. autoclass:: iConfigManager - -Database and service attachments --------------------------------- -.. autoclass:: iProvider -.. autoclass:: iAttachment_v3 -.. autoclass:: iAttachment_v4 -.. autoclass:: iAttachment -.. autoclass:: iService_v3 -.. autoclass:: iService_v4 -.. autoclass:: iService -.. autoclass:: iXpbBuilder - -Blobs ------ -.. autoclass:: iBlob_v3 -.. autoclass:: iBlob - -Transactions ------------- -.. autoclass:: iTransaction_v3 -.. autoclass:: iTransaction -.. autoclass:: iDtcStart -.. autoclass:: iDtc - -Metadata --------- -.. autoclass:: iMessageMetadata_v3 -.. autoclass:: iMessageMetadata -.. autoclass:: iMetadataBuilder_v3 -.. autoclass:: iMetadataBuilder - -SQL execution -------------- -.. autoclass:: iStatement_v3 -.. autoclass:: iStatement_v4 -.. autoclass:: iStatement -.. autoclass:: iResultSet_v3 -.. autoclass:: iResultSet -.. autoclass:: iBatch_v3 -.. autoclass:: iBatch -.. autoclass:: iBatchCompletionState - -Events ------- -.. autoclass:: iEvents_v3 -.. autoclass:: iEvents - -Utilities ---------- -.. autoclass:: iTimerControl -.. autoclass:: iUtil_v2 -.. autoclass:: iUtil -.. autoclass:: iDecFloat16 -.. autoclass:: iDecFloat34 -.. autoclass:: iInt128 - -Other ------ -.. autoclass:: iPluginManager -.. autoclass:: iRequest_v3 -.. autoclass:: iRequest - -Interface implementations -========================= - -.. autoclass:: iVersionedImpl -.. autoclass:: iReferenceCountedImpl -.. autoclass:: iDisposableImpl -.. autoclass:: iVersionCallbackImpl -.. autoclass:: iCryptKeyCallbackImpl -.. autoclass:: iOffsetsCallbackImp -.. autoclass:: iEventCallbackImpl -.. autoclass:: iTimerImpl - diff --git a/docs/ref-types.txt b/docs/ref-types.txt deleted file mode 100644 index 36871e3..0000000 --- a/docs/ref-types.txt +++ /dev/null @@ -1,214 +0,0 @@ -.. module:: firebird.driver.types - :synopsis: Firebird driver types - -===================== -firebird.driver.types -===================== - -Exceptions -========== - -Next exceptions are required by Python DB API 2.0 - -`Error` is imported from `firebird.base.types`. - -.. autoexception:: Error -.. autoexception:: InterfaceError -.. autoexception:: DatabaseError -.. autoexception:: DataError -.. autoexception:: OperationalError -.. autoexception:: IntegrityError -.. autoexception:: InternalError -.. autoexception:: ProgrammingError -.. autoexception:: NotSupportedError -.. autoexception:: FirebirdWarning - -This is the exception inheritance layout:: - - StandardError - |__UserWarning - |__FirebirdWarning - |__Error - |__InterfaceError - |__DatabaseError - |__DataError - |__OperationalError - |__IntegrityError - |__InternalError - |__ProgrammingError - |__NotSupportedError - -Other constants and types required by Python DB API 2.0 specification -===================================================================== - -Globals -------- - -.. autodata:: apilevel - :no-value: - -.. autodata:: threadsafety - :no-value: - -.. autodata:: paramstyle - :no-value: - -Helper constants for work with :attr:`.Cursor.description` content ------------------------------------------------------------------- - -- DESCRIPTION_NAME -- DESCRIPTION_TYPE_CODE -- DESCRIPTION_DISPLAY_SIZE -- DESCRIPTION_INTERNAL_SIZE -- DESCRIPTION_PRECISION -- DESCRIPTION_SCALE -- DESCRIPTION_NULL_OK - -Types ------ - -.. autodata:: STRING - :no-value: - -.. autodata:: BINARY - :no-value: - -.. autodata:: NUMBER - :no-value: - -.. autodata:: DATETIME - :no-value: - -.. autodata:: ROWID - :no-value: - -Constructors for data types ---------------------------- - -.. autodata:: Date -.. autodata:: Time -.. autodata:: Timestamp -.. autofunction:: DateFromTicks -.. autofunction:: TimeFromTicks -.. autofunction:: TimestampFromTicks -.. autodata:: Binary - -Types for type hints -==================== - -.. autodata:: DESCRIPTION -.. autodata:: CB_OUTPUT_LINE -.. autoclass:: Transactional - -Enums -===== - -.. autoclass:: NetProtocol -.. autoclass:: DirectoryCode -.. autoclass:: XpbKind -.. autoclass:: StateResult -.. autoclass:: PageSize -.. autoclass:: DBKeyScope -.. autoclass:: InfoItemType -.. autoclass:: SrvInfoCode -.. autoclass:: BlobInfoCode -.. autoclass:: DbInfoCode -.. autoclass:: ResultSetInfoCode -.. autoclass:: Features -.. autoclass:: ReplicaMode -.. autoclass:: StmtInfoCode -.. autoclass:: ReqInfoCode -.. autoclass:: ReqState -.. autoclass:: TraInfoCode -.. autoclass:: TraInfoIsolation -.. autoclass:: TraInfoReadCommitted -.. autoclass:: TraInfoAccess -.. autoclass:: TraAccessMode -.. autoclass:: TraIsolation -.. autoclass:: TraReadCommitted -.. autoclass:: Isolation -.. autoclass:: TraLockResolution -.. autoclass:: TableShareMode -.. autoclass:: TableAccessMode -.. autoclass:: DefaultAction -.. autoclass:: StatementType -.. autoclass:: SQLDataType -.. autoclass:: DPBItem -.. autoclass:: TPBItem -.. autoclass:: SPBItem -.. autoclass:: BPBItem -.. autoclass:: BlobType -.. autoclass:: BlobStorage -.. autoclass:: ServerAction -.. autoclass:: SrvDbInfoOption -.. autoclass:: SrvRepairOption -.. autoclass:: SrvBackupOption -.. autoclass:: SrvRestoreOption -.. autoclass:: SrvNBackupOption -.. autoclass:: SrvTraceOption -.. autoclass:: SrvPropertiesOption -.. autoclass:: SrvValidateOption -.. autoclass:: SrvUserOption -.. autoclass:: DbAccessMode -.. autoclass:: DbSpaceReservation -.. autoclass:: DbWriteMode -.. autoclass:: ShutdownMode -.. autoclass:: OnlineMode -.. autoclass:: ShutdownMethod -.. autoclass:: TransactionState -.. autoclass:: DbProvider -.. autoclass:: DbClass -.. autoclass:: Implementation -.. autoclass:: ImpCPU -.. autoclass:: ImpOS -.. autoclass:: ImpCompiler -.. autoclass:: CancelType -.. autoclass:: DecfloatRound -.. autoclass:: DecfloatTraps - -Flags -===== - -.. autoclass:: StateFlag -.. autoclass:: PreparePrefetchFlag -.. autoclass:: StatementFlag -.. autoclass:: CursorFlag -.. autoclass:: ConnectionFlag -.. autoclass:: EncryptionFlag -.. autoclass:: ServerCapability -.. autoclass:: SrvRepairFlag -.. autoclass:: SrvStatFlag -.. autoclass:: SrvBackupFlag -.. autoclass:: SrvRestoreFlag -.. autoclass:: SrvNBackupFlag -.. autoclass:: SrvPropertiesFlag -.. autoclass:: ImpFlags - -Dataclasses -=========== - -.. autoclass:: ItemMetadata - :no-members: - -.. autoclass:: TableAccessStats - :no-members: - -.. autoclass:: UserInfo - :no-members: - -.. autoclass:: BCD - :no-members: - -.. autoclass:: TraceSession - :no-members: - -.. autoclass:: ImpData - :no-members: - -.. autoclass:: ImpDataOld - :no-members: - -Helper functions -================ - -.. autofunction:: get_timezone diff --git a/docs/reference.txt b/docs/reference.txt deleted file mode 100644 index 3209a7c..0000000 --- a/docs/reference.txt +++ /dev/null @@ -1,19 +0,0 @@ - -######################### -Firebird-driver Reference -######################### - -Driver modules -============== - -.. toctree:: - :maxdepth: 2 - - ref-main - ref-types - ref-config - ref-core - ref-hooks - ref-intf - ref-fbapi - diff --git a/docs/requirements.txt b/docs/requirements.txt deleted file mode 100644 index 613891a..0000000 --- a/docs/requirements.txt +++ /dev/null @@ -1,4 +0,0 @@ -sphinx-bootstrap-theme>=0.8.1 -sphinx-autodoc-typehints>=1.24.0 -sphinx==7.2.6 -. diff --git a/docs/usage-guide.txt b/docs/usage-guide.txt deleted file mode 100644 index 88916ef..0000000 --- a/docs/usage-guide.txt +++ /dev/null @@ -1,3278 +0,0 @@ - -=========== -Usage Guide -=========== - -.. currentModule:: firebird.driver - -Driver structure -================ - -Source code is currently divided into next submodules: - -* :mod:`~firebird.driver.types` - Data types used by driver. -* :mod:`~firebird.driver.interfaces` - Interface wrappers for Firebird new API -* :mod:`~firebird.driver.core` - Main driver source code. -* :mod:`~firebird.driver.fbapi` - Python `ctypes` interface to Firebird client library. -* :mod:`~firebird.driver.config` - Driver configuration. -* :mod:`~firebird.driver.hooks` - Drivers hooks. - -All important data, functions, classes and constants are available directly in `firebird.driver` -name space. In normal circumstances is not necessary to import sub-modules directly. However, -you may need them to access some not so frequently needed driver functionality like driver -hooks, or to implement your own callback interfaces. - -.. important:: - - `firebird-driver` is designed to support all Firebird versions starting from version 3.0. - Because each Firebird major version adds new functionality, and Firebird OO API could - be extended even in maintenance releases, the driver isolates volatile functionality - into special class hierarchies. - - For example information about database (provided via `~.iAttachment_v3.get_info()` API - call) is isolated into separate `.DatabaseInfoProvider` class hierarchy. - The `.Connection.info` attribute then provides access to instance of appropriate class - - `.DatabaseInfoProvider` or its ancestor - for connected database. - The `.DatabaseInfoProvider` class **always** provides functionality of most recent - Firebird version supported by driver. - - This layout has several important consequences: - - 1. The `.DatabaseInfoProvider` class may change in major driver release if new Firebird - functionality is introduced. This normally represent no problems for client application - as backward compatibility is guaranteed. - 2. You should check the class hierarchy for "evolving" classes when you start using the - driver, and whenever you upgrade to new **major** driver version. If there are versioned - ancestor classes (they always have Firebird version number in their name) for canonical - (top level) ones, you should adjust your application to deal with situations when - instance of ancestor class is provided by driver instead top-level one, to prevent - run-time exceptions caused by access to functionality not provided by currently attached - Firebird server. - - .. note:: - - The same apply for low-level API (`~firebird.driver.interfaces`) with difference - that they may change in minor driver releases (because API could be extended in - Firebird maintenance releases). - - .. seealso:: - - `.DatabaseInfoProvider`, `.TransactionInfoProvider`, `.ServerInfoProvider`, - `.ServerDbServices`, `.ServerUserServices` and `.ServerTraceServices`. - -.. index:: Configuration - -Configuration -============= - -The driver uses configuration built on top of `configuration system ` -provided by `firebird-base`_ package. In addition to global settings, the configuration -also includes the definition of connection parameters to Firebird servers and databases. - -The default configuration connects to embedded server using direct/local connection method. -To access remote servers and databases (or local ones through remote protocols), it's -necessary to adjust default configuration, or `register` them in configuration manager. - -You can manipulate the configuration objects directly, or load configuration from files or -strings (in `.ini-style` `configparser` format). - -The 'driver_config' object --------------------------- - -The global `.driver_config` object holds all configurable driver parameters, and access -configuration parameters for registered Firebird servers and databases. - -In initial state, all parameters have default values and there are no registered servers -and databases. You can set individual parameter values directly, or you can set multiple -parameters (including registered servers and databases) at once by loading them from -configuration string, dict or file(s). - -.. important:: - - If you want to use specific Firebird client library, you must set the value of - `.DriverConfig.fb_client_library` configuration option **before** your application - calls any from following functions: `.connect()`, `~firebird.driver.core.create_database()`, - `.connect_server()`, `.load_api()` or `.get_api()`. - -.. seealso:: - - `.DriverConfig` for list of available methods and parameters. - -Server and database configuration ---------------------------------- - -Firebird provides ever-increasing list of parameter options for database and server connections. -To keep the Python API clean and manageable, the `firebird-driver` uses server and database -configuration objects instead function parameters to specify values for almost all such options. -Connection functions then provide a name parameter that can refer to particular server / database -or configuration, and few keyword parameters to specify / override selected options. - -.. important:: - - The configuration objects does not allow specification of next options: - - - set database encryption callback (for technical reasons) - - set db_key scope (for security reasons) - - disable garbage collection (for security reasons) - - disable database triggers (for security reasons) - - allow overwrite of existing database with newly created database (for security reasons) - - These options could be specified only as keyword arguments in appropriate functions. - -.. seealso:: - - `.ServerConfig` and `.DatabaseConfig` for list of available methods and parameters. - - - -.. index:: Database - pair: Connection; creation - -Databases -========= - -Access to the database is made available through `.Connection` objects. Firebird-driver -provides two constructors for these: - -* `.connect` - Returns `.Connection` to database that already exists. -* `~firebird.driver.core.create_database` - Returns `.Connection` to newly created database. - - -.. index:: - pair: Database; connect - -Using connect() ---------------- - -This constructor has one positional and several keyword parameters. - -The value of `database` positional parameter must be one of: - -* name of registered database configuration -* database name / alias - -.. important:: This value **cannot** be DSN / fully qualified Firebird connection string! - -Keyword parameters are intended to override selected configuration options, or to specify -options that are not configurable. - -.. note:: - - If `database` value is not recognized as name of registered database configuration, - the driver uses `~.DriverConfig.db_defaults` and `~.DriverConfig.server_defaults` - configuration objects. - - -A simple database connection is typically established with code such as this: - -.. sourcecode:: python - - from firebird.driver import connect - - # Attach to 'employee' database/alias using embedded server connection - con = connect('employee', user='sysdba', password='masterkey') - - # Attach to 'employee' database/alias using local server connection - from firebird.driver import driver_config - driver_config.server_defaults.host.value = 'localhost' - con = connect('employee', user='sysdba', password='masterkey') - - # Set 'user' and 'password' via configuration - driver_config.server_defaults.user.value = 'SYSDBA' - driver_config.server_defaults.password.value = 'masterkey' - con = connect('employee') - -However, it's recommended to use specific configuration for servers and databases. -It's possible to register servers and databases directly in code like this: - -.. sourcecode:: python - - from firebird.driver import connect, driver_config - - # Register Firebird server - srv_cfg = """[local] - host = localhost - user = SYSDBA - password = masterkey - """ - driver_config.register_server('local', srv_cfg) - - # Register database - db_cfg = """[employee] - server = local - database = employee.fdb - protocol = inet - charset = utf8 - """ - driver_config.register_database('employee', db_cfg) - - # Attach to 'employee' database - con = connect('employee') - -But more convenient approach is using single configuration file:: - - # file: myapp.cfg - - [firebird.driver] - servers = local - databases = employee - - [local] - host = localhost - user = SYSDBA - password = masterkey - - [employee] - server = local - database = employee.fdb - protocol = inet - charset = utf8 - -.. sourcecode:: python - - from firebird.driver import connect, driver_config - - driver_config.read('myapp.cfg') - - # Attach to 'employee' database - con = connect('employee') - -.. seealso:: `.connect()` for details. - -.. index:: - pair: Database; create - -Using create_database() ------------------------ - -This constructor returns connection to newly created database. It works in the same way -as `.connect()`, but utilizes additional database configuration options. - -It's possible to specify these options in code like this: - -.. sourcecode:: python - - from firebird.driver import connect, driver_config - - # Register Firebird server - srv_cfg = """[local] - host = localhost - user = SYSDBA - password = masterkey - """ - driver_config.register_server('local', srv_cfg) - - # Register database - db_cfg = """[mydb] - server = local - database = mydb.fdb - protocol = inet - charset = utf8 - # create options - page_size = 16384 - db_charset = utf8 - sweep_interval = 80000 - reserve_space = no - """ - driver_config.register_database('mydb', db_cfg) - - # create 'mydb' database - con = create_database('mydb') - -But more convenient approach is using single configuration file:: - - # file: myapp.cfg - - [firebird.driver] - servers = local - databases = mydb - - [local] - host = localhost - user = SYSDBA - password = masterkey - - [mydb] - server = local - database = mydb.fdb - protocol = inet - charset = utf8 - # create options - page_size = 16384 - db_charset = utf8 - sweep_interval = 80000 - reserve_space = no - -.. sourcecode:: python - - from firebird.driver import create_database, driver_config - - driver_config.read('myapp.cfg') - - # create 'mydb' database - con = create_database('mydb') - -.. seealso:: `~firebird.driver.core.create_database()` for details. - -.. index:: - pair: Database; delete - -Deleting databases ------------------- - -The Firebird engine also supports dropping (deleting) databases dynamically, -but dropping is a more complicated operation than creating, for several reasons: -an existing database may be in use by users other than the one who requests -the deletion, it may have supporting objects such as temporary sort files, and -it may even have dependent shadow databases. Although the database engine -recognizes a `DROP DATABASE` SQL statement, support for that statement is limited -to the `isql` command-line administration utility. However, the engine supports -the deletion of databases via an API call, which `firebird-driver` exposes as -`~.Connection.drop_database` method in `.Connection` class. So, to drop a database -you need to connect to it first. - -**Example:** - -.. sourcecode:: python - - from firebird.driver import connect, driver_config - - driver_config.read('myapp.cfg') - - # Attach to 'myapp' database - con = connect('myapp') - con.drop_database() - -.. seealso:: `.Connection.drop_database()` for details. - -.. index:: - pair: Connection; usage - pair: connection; Database - -Connection object ------------------ - -`.Connection` object represents a direct link to database, and works as -gateway for next operations with it: - -* `Executing SQL Statements`_: methods `~.Connection.execute_immediate()` and `~.Connection.cursor()`. -* `Dropping database `_: method `~.Connection.drop_database()`. -* `Transanction management`_: methods `~.Connection.begin()`, `~.Connection.commit()`, - `~.Connection.rollback()`, `~.Connection.savepoint()`, `~.Connection.transaction_manager()`, - `~.Connection.is_active()`, and attributes `~.Connection.main_transaction`, - `~.Connection.query_transaction`, `~.Connection.transactions` and `~.Connection.default_tpb`. -* Work with `Database Events`_: method `~.Connection.event_collector`. -* `Getting information about connection`_: methods `~.Connection.is_closed()` and - `~.Connection.ping()` and attributes `~.Connection.dsn`, `~.Connection.charset` - and `~.Connection.sql_dialect`. -* `Getting information about database`_: attribute `~.Connection.info`. -* `Closing the connection`_: method `~.Connection.close()` - -.. index:: - pair: Connection; closing - -Closing the connection ----------------------- - -There are many local and server resources used by firebird-driver that must be properly -managed, and disposed when they are no longer necessary. All objects that require proper -finalization provide `close()` method that must be called when object is no longer needed. -The `.Connection` (and `.Server`) objects are the most important ones, as other most frequently -used objects like cursors, prepared statements and transactions are typically associated with -connections. - -You may call the `close()` method directly, or use the :ref:`with ` statement -and context manager support provided by all these objects. - -**Example:** - -.. sourcecode:: python - - from firebird.driver import connect, driver_config - - driver_config.read('myapp.cfg') - - with connect('employee') as con: - cur = con.cursor() - cur.execute('select 1 from rdb$database') - print(cur.fetchone()[0]) - - -.. note:: - - Objects that require proper finalization are: `.Connection`, `.TransactionManager` - and `.DistributedTransactionManager`, `.Statement`, `.BlobReader`, `.Cursor` and `.Server`. - - Although only `.Connection` and `.Server` objects must be closed directly because - all other objects are associated with them and thus closed when connection is - closed, it's **recommended** to directly close any resource object obtained by - your code when it's no longer needed (either directly by calling `close()` or using - `with` statement). - -.. important:: - - All managed objects have `~object.__del__` method, which ensures that the object in - the active state is properly closed before it is destroyed by the Python memory manager. - However, **the close operation may fail** as the state of your application could be arbitrary - and the sequence in which objects are disposed by memory manager is not deterministic. - - The `~object.__del__` methods should be thus considered as safe guard of last resort - that your code should not rely upon. To indicate that your code is not managing - resources properly, the `ResourceWarning` is raises when active object is disposed - by memory manager. - - .. note:: - - Such warnings may not reach your attention if warnings are disabled or filtered - on your system. You should always develop and test your applications with enabled - delivery of resource warnings. - -.. seealso:: `.Connection.close()` for details. - -.. index:: - pair: Connection; information about - -Getting information about connection ------------------------------------- - -Only (most useful) part of information associated with `.Connection` object is directly -available: - -* It's possible to check whether Connection object is closed or not with - `~.Connection.is_closed()` method. -* It's possible to check whether connection to the Firebird server is not broken with - `~.Connection.ping()` method. -* The DSN (fully qualified Firebird database connection string) is surfaced as `~.Connection.dsn` - read-only property. -* The character set used by Connection is surfaced as `~.Connection.charset` read-only property. -* The SQL dialect used by Connection is surfaced as `~.Connection.sql_dialect` read-only property. - -.. tip:: - - Additional connection-specific information is currently held as `bytes` in protected - `Connection._dpb` attribute that could be processed using `~firebird.driver.core.DPB` object. - -.. index:: - pair: Database; information about - -Getting information about database ----------------------------------- - -.. important:: - - Because the scope and type of database information depends on the version of the Firebird - server and database ODS, this information is made available through a separate class - `.DatabaseInfoProvider`. The `.Connection.info` property provides access to - instance of `.DatabaseInfoProvider` or it's **ancestor** class according to ODS of attached - database and Firebird version. - -Although you may query the information directly from server using -`~firebird.driver.core.DatabaseInfoProvider3.get_info()` method (that wraps the Firebird -`.iAttachment.getInfo()` API call), the `.DatabaseInfoProvider` object -provides more convenient methods and properties for obtaining specific information directly. - -.. note:: - - Some information provided by `.DatabaseInfoProvider` properties - (like `~.DatabaseInfoProvider3.cache_hit_ratio`) could not be obtained via - `get_info()` method. - - -**Example:** - -.. sourcecode:: python - - from firebird.driver import connect - - with connect('employee', user='SYSDBA', password='masterkey') as con: - print(f"Database character set: {con.info.charset}") - print(f"Page size (in bytes): {con.info.page_size}") - print(f"Attachment ID: {con.info.id}") - print(f"SQL dialect used by connected database: {con.info.sql_dialect}") - print(f"Database name (filename or alias): {con.info.name}") - print(f"Database site name: {con.info.site}") - print(f"Implementation (old format): {con.info.implementation!s}") - print(f"Database Provider: {con.info.provider!s}") - print(f"Database Class: {con.info.db_class!s}") - print(f"Date when database was created: {con.info.creation_date}") - print(f"Size of page cache used by connection: {con.info.page_cache_size}") - print(f"Number of pages allocated for database: {con.info.pages_allocated}") - print(f"Number of database pages in active use: {con.info.pages_used}") - print(f"Number of free allocated pages in database: {con.info.pages_free}") - print(f"Sweep interval: {con.info.sweep_interval}") - print(f"Data page space usage (USE_FULL or RESERVE): {con.info.space_reservation!s}") - print(f"Database write mode (SYNC or ASYNC): {con.info.write_mode!s}") - print(f"Database access mode (READ_ONLY or READ_WRITE): {con.info.access_mode!s}") - print(f"Current I/O statistics - Reads from disk to page cache: {con.info.reads}") - print(f"Current I/O statistics - Fetches from page cache: {con.info.fetches}") - print(f"Cache hit ratio = 1 - (reads / fetches): {con.info.cache_hit_ratio}") - print(f"Current I/O statistics - Writes from page cache to disk: {con.info.writes}") - print(f"Current I/O statistics - Writes to page in cache: {con.info.marks}") - print(f"Total amount of memory curretly used by database engine: {con.info.current_memory}") - print(f"Max. total amount of memory so far used by database engine: {con.info.max_memory}") - print(f"ID of Oldest Interesting Transaction: {con.info.oit}") - print(f"ID of Oldest Active Transaction: {con.info.oat}") - print(f"ID of Oldest Snapshot Transaction: {con.info.ost}") - print(f"ID for next transaction: {con.info.next_transaction}") - -**Sample output**:: - - Database character set: NONE - Page size (in bytes): 8192 - Attachment ID: 378 - SQL dialect used by connected database: 3 - Database name (filename or alias): /opt/firebird/examples/empbuild/employee.fdb - Database site name: NewAmarisk - Implementation (old format): Implementation.RDB_VMS - Database Provider: DbProvider.FIREBIRD - Database Class: DbClass.SERVER_ACCESS - Date when database was created: 2020-05-13 10:13:57.005010 - Size of page cache used by connection: 2048 - Number of pages allocated for database: 346 - Number of database pages in active use: 311 - Number of free allocated pages in database: 35 - Sweep interval: 20000 - Data page space usage (USE_FULL or RESERVE): DbSpaceReservation.RESERVE - Database write mode (SYNC or ASYNC): DbWriteMode.SYNC - Database access mode (READ_ONLY or READ_WRITE): DbAccessMode.READ_WRITE - Current I/O statistics - Reads from disk to page cache: 87 - Current I/O statistics - Fetches from page cache: 1525 - Cache hit ratio = 1 - (reads / fetches): 0.9429508196721311 - Current I/O statistics - Writes from page cache to disk: 2 - Current I/O statistics - Writes to page in cache: 5 - Total amount of memory curretly used by database engine: 21925248 - Max. total amount of memory so far used by database engine: 22033760 - ID of Oldest Interesting Transaction: 307 - ID of Oldest Active Transaction: 308 - ID of Oldest Snapshot Transaction: 308 - ID for next transaction: 308 - -.. seealso:: `.DatabaseInfoProvider` for details. - -Getting information about Firebird version -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -Because functionality and some features depends on actual Firebird version, it could be -important for driver users to check it. This (otherwise) simple task could be confusing -for new Firebird users, because Firebird uses two different version lineages. This abomination -was introduced to Firebird thanks to its InterBase legacy (Firebird 1.0 is a fork of InterBase -6.0), as applications designed to work with InterBase can often work with Firebird without -problems (and vice versa). - -`.DatabaseInfoProvider` provides these version strings as two properties: - -* `~.DatabaseInfoProvider.server_version` - Legacy InterBase-friendly version string. -* `~.DatabaseInfoProvider.firebird_version` - Firebird’s own version string. - -However, this version string contains more information than version number. For example for -Linux Firebird 4.0.0 it’s ‘LI-T4.0.0.1963 Firebird 4.0 Beta 2’. So `.DatabaseInfoProvider` -provides two more properties for your convenience: - -* `~.DatabaseInfoProvider.version` - Only Firebird version number. It’s a string with - format: major.minor.subrelease.build -* `~.DatabaseInfoProvider.engine_version` - Engine (major.minor) version as (float) number. - - -**Example:** - -.. sourcecode:: python - - from firebird.driver import connect - - with connect('employee', user='SYSDBA', password='masterkey') as con: - print(f"server_version: '{con.info.server_version}'") - print(f"firebird_version: '{con.info.firebird_version}'") - print(f"version: '{con.info.version}'") - print(f"engine_version: {con.info.engine_version}") - -**Sample output**:: - - server_version: 'LI-T6.3.0.1963 Firebird 4.0 Beta 2' - firebird_version: 'LI-T4.0.0.1963 Firebird 4.0 Beta 2' - version: '4.0.0.1963' - engine_version: 4.0 - -Database On-Disk Structure -^^^^^^^^^^^^^^^^^^^^^^^^^^ - -Particular Firebird features may also depend on specific support in database -(for example number and structure of monitoring tables). These required structures are -present automatically when database is created by particular engine verison that needs -them, but Firebird engine may work with databases created by older versions and thus with -older structure, so it could be necessary to consult also On-Disk Structure (ODS for short) -version. `.DatabaseInfoProvider` provides this number as `~.DatabaseInfoProvider.ods` (float) -property. - -**Example:** - -.. sourcecode:: python - - from firebird.driver import connect - - with connect('employee', user='SYSDBA', password='masterkey') as con: - print(f"ods: {con.info.ods}") - print(f"ods_version: {con.info.ods_version}") - print(f"ods_minor_version: {con.info.ods_minor_version}") - -**Sample output**:: - - ods: 13.0 - ods_version: 13 - ods_minor_version: 0 - - - -.. index:: SQL Statement - -Executing SQL Statements -======================== - -Firebird-driver implements two ways for execution of SQL commands against connected database: - -* `~.Connection.execute_immediate` - for execution of SQL commands that don't return any result. -* `.Cursor` objects that offer rich interface for execution of SQL commands and fetching their results. - - -.. index:: - pair: Cursor; usage - -Cursor object -------------- - -Because `.Cursor` objects always operate in context of single `.Connection` (and `.TransactionManager`), -`.Cursor` instances are not created directly, but by constructor method. Python DB API 2.0 assumes -that if database engine supports transactions, it supports only one transaction per connection, -hence it defines constructor method `~.Connection.cursor` (and other transaction-related methods) -as part of `.Connection` interface. However, Firebird supports multiple independent transactions -per connection. To conform to Python DB API, firebird-driver uses concept of internal -`~.Connection.main_transaction` and secondary `~.Connection.transactions`. Cursor constructor is -primarily defined by `.TransactionManager`, and Cursor constructor on `.Connection` is therefore -a shortcut for `main_transaction.cursor()`. - -`.Cursor` objects are used for next operations: - -* Execution of SQL Statemets: methods `~.Cursor.execute()`, `~.Cursor.executemany()`, `~.Cursor.open()` - and `~.Cursor.callproc()`. -* Creating `.Statement` objects for efficient repeated execution of SQL statements, and to obtain - additional information about SQL statements (like execution `~.Statement.plan`): method `~.Cursor.prepare()`. -* `Fetching results `_: methods `~.Cursor.fetchone()`, `~.Cursor.fetchmany()`, - `~.Cursor.fetchall()`, `~.Cursor.fetch_next()`, `~.Cursor.fetch_prior()`, `~.Cursor.fetch_first()`, - `~.Cursor.fetch_last()`, `~.Cursor.fetch_absolute()` and `~.Cursor.fetch_relative()`. - -.. index:: - pair: SQL Statement; execution - -SQL Execution Basics --------------------- - -There are five methods how to execute SQL commands: - -1. `.Connection.execute_immediate()` or `.TransactionManager.execute_immediate()` for SQL commands - that don't return any result, and are not executed frequently. This method also **doesn't** - support either `parameterized statements `_ or - `prepared statements `_. - - .. tip:: - - This method is efficient for `administrative` and `DDL`_ SQL commands, like `DROP`, `CREATE` - or `ALTER` commands, `SET STATISTICS` etc. - -2. `.Cursor.execute()` for SQL commands that return result sets, i.e. sequence of `rows` of the same - structure, and sequence has unknown number of `rows` (including zero). Each row of the sequence - can be read only once, and is returned in the order it is read from the server. - - .. tip:: - - This method is preferred for all `SELECT` and other `DML`_ statements, or any statement that - is executed frequently, either `as is` or in `parameterized` form. - -3. `.Cursor.executemany()` for execution of single parameterized SQL command with various set - of parameters. - - .. important:: - - Because `executemany()` is basically a simple loop that calls `execute()` with different - parameters, it's possible to execute any statement acceptable by `execute()`. However, - it's possible to access the result set **only** from last executed command, so this method - should not be used for SQL commands that return results. - -4. `.Cursor.open()` for SQL command that return result sets, i.e. sequence of `rows` of the same - structure, and sequence has unknown number of `rows` (including zero). Instead of just fetching - rows sequentially in a forward direction like `execute()`, this method allows flexible navigation - through an open cursor set both backwards and forwards. Rows next to, prior to and relative to - the current cursor row can be targeted. - - .. seealso:: `Scrollable cursors `_ for details. - -5. `.Cursor.callproc()` for execution of `Stored procedures` that always return exactly one set - of values. - - .. note:: - - This method of SP invocation is equivalent to `"EXECUTE PROCEDURE ..."` SQL statement. - -.. index:: - pair: Cursor; fetching data - -Fetching data from server -------------------------- - -Result of SQL statement execution consists from sequence of zero to unknown number of `rows`, -where each `row` is a set of exactly the same number of values. `.Cursor` object offer number -of different methods for fetching these `rows`, that should satisfy all your specific needs: - -* `~.Cursor.fetchone()` - Returns the next row of a query result set, or `None` when no more data - is available. - - .. tip:: - - Cursor supports the :ref:`iterator protocol `, yielding tuples of values - like `~.Cursor.fetchone()`. - -* `~.Cursor.fetchmany()` - Returns the next set of rows of a query result, returning a sequence - of sequences (e.g. a list of tuples). An empty sequence is returned when no more rows are available. - - The number of rows to fetch per call is specified by the parameter. If it is not given, the - cursor’s `~.Cursor.arraysize` determines the number of rows to be fetched. The method does try - to fetch as many rows as indicated by the size parameter. If this is not possible due to - the specified number of rows not being available, fewer rows may be returned. - - .. note:: - - The default value of `~.Cursor.arraysize` is `1`, so without paremeter it's equivalent to - `~.Cursor.fetchone()`, but returns list of `rows`, instead actual `row` directly. - -* `~.Cursor.fetchall()` - Returns all (remaining) rows of a query result as list of tuples, - where each tuple is one row of returned values. - - .. tip:: - - This method can potentially return huge amount of data, that may exhaust available memory. - If you need just `iteration` over potentially big result set, use loops with `~.Cursor.fetchone()` - or Cursor's built-in support for :ref:`iterator protocol ` instead this method. - -* Call to `~.Cursor.execute()` returns `self` (Cursor instance) that itself supports the - :ref:`iterator protocol `, yielding tuples of values like `~.Cursor.fetchone()`. - -.. important:: - - Firebird-driver makes absolutely no guarantees about the `row` return value of the - `fetch*()` methods except that it is a sequence indexed by field position. Therefore, client - programmers should not rely on the return value being an instance of a particular class or type. - -**Examples:** - -.. sourcecode:: python - - from firebird.driver import connect - - with connect('employee', user='SYSDBA', password='masterkey') as con: - cur = con.cursor() - SELECT = "select country, currency from country" - - # 1. Using built-in support for iteration protocol to iterate over the rows available - # from the cursor, unpacking the resulting sequences to yield their elements (country, currency): - cur.execute(SELECT) - for (country, currency) in cur: - print(f"{country} uses {currency} as currency.") - # or alternatively you can take an advantage of cur.execute() returning self. - for (country, currency) in cur.execute(SELECT): - print(f"{country} uses {currency} as currency.") - - # 2. Equivalently using fetchall(): - # This is potentially dangerous if result set is huge, as the whole result set is - # first materialized as list and then used for iteration. - cur.execute(SELECT) - for row in cur.fetchall(): - print(f"{row[0]} uses {row[1]} as currency.") - -.. important:: - - Method `.Cursor.executemany()` is not intended for operations that return results, - so it does **NOT** returns `self` like `.Cursor.execute()`, and you can't use calls - to this method as iterator. - -.. _scrollable-cursors: - -.. index:: - pair: Cursor; scrollable - -Scrollable cursors ------------------- - -SQL statements executed by `.Cursor.open()` have scrollable result set that could be -navigated using next methods: - -* `~.Cursor.fetch_next()` - Moves the cursor's current position to the next row and - returns it. Returns `None` if the cursor is empty or already positioned at the last row. - -* `~.Cursor.fetch_prior()` - Moves the cursor's current position to the prior row and - returns it. Returns `None` if the cursor is empty or already positioned at the first row. - -* `~.Cursor.fetch_first()` - Moves the cursor's current position to the first row and - returns it. Returns `None` if the cursor is empty. - -* `~.Cursor.fetch_last()` - Moves the cursor's current position to the last row and - returns it. Returns `None` if the cursor is empty. - -* `~.Cursor.fetch_absolute()` - Moves the cursor's current position to the specified - and returns the located row. Returns `None` if is beyond the - cursor's boundaries. - -* `~.Cursor.fetch_relative()` - Moves the cursor's current position backward or forward - by the specified and returns the located row. Returns `None` if the calculated - position is beyond the cursor's boundaries. - -.. important:: - - Please note that scrollable cursors: - - a) are not supported by all versions of Firebird server. - - b) are internally materialized as a temporary record set, thus consuming - memory/disk resources, so this feature should be used only when really necessary. - -**Example:** - -.. sourcecode:: python - - from firebird.driver import connect - - def print_row(row): - if row: - print(f"{row[0]}, {row[1]}, {row[2]}") - else: - print('NO DATA') - - with connect('employee', user='SYSDBA', password='masterkey') as con: - cur = con.cursor() - cur.open('select row_number() over (order by country), country, currency from country order by country') - - # You can iterate over scrollable cursors - for row in cur: - print_row(row) - - print('-' * 10) - # or fetch particular rows directly - print_row(cur.fetch_first()) - print_row(cur.fetch_last()) - print_row(cur.fetch_absolute(10)) - print_row(cur.fetch_next()) - print_row(cur.fetch_prior()) - print_row(cur.fetch_relative(-5)) - print_row(cur.fetch_relative(10)) - - print('-' * 10) - - cur.fetch_last() - print_row(cur.fetch_next()) - -**Sample output**:: - - 1, Australia, ADollar - 2, Austria, Euro - 3, Belgium, Euro - 4, Canada, CdnDlr - 5, England, Pound - 6, Fiji, FDollar - 7, France, Euro - 8, Germany, Euro - 9, Hong Kong, HKDollar - 10, Italy, Euro - 11, Japan, Yen - 12, Netherlands, Euro - 13, Romania, RLeu - 14, Russia, Ruble - 15, Switzerland, SFranc - 16, USA, Dollar - ---------- - 1, Australia, ADollar - 16, USA, Dollar - 10, Italy, Euro - 11, Japan, Yen - 10, Italy, Euro - 5, England, Pound - 15, Switzerland, SFranc - ---------- - NO DATA - -.. index:: - pair: SQL Statement; parameterized - -.. _parameterized-statements: - -Parameterized statements ------------------------- - -When SQL command you want to execute contains data `values`, you can either: - -* Embed them `directly` or via `string formatting` into command string, e.g.: - - .. sourcecode:: python - - cur.execute("insert into the_table (a,b,c) values ('aardvark', 1, 0.1)") - # or - cur.execute("select * from the_table where col == 'aardvark'") - # or - cur.execute("insert into the_table (a,b,c) values ('%s', %i, %f)" % ('aardvark',1,0.1)) - # or - cur.execute(f"select * from the_table where col == '{value}'") - -* Use parameter marker (`?`) in command string in the slots where values are expected, - then supply those values as Python list or tuple: - - .. sourcecode:: python - - cur.execute("insert into the_table (a,b,c) values (?,?,?)", ('aardvark', 1, 0.1)) - # or - cur.execute("select * from the_table where col == ?",('aardvark',)) - -While both methods have the same results, the second one (called `parametrized`) has several -important advantages: - -* You don't need to handle conversions from Python data types to strings. -* Firebird-driver will handle all data type conversions (if necessary) from Python data types - to Firebird ones, including `None/NULL` conversion and conversion from `str` to `bytes` - in encoding expected by server. -* You may pass BLOB values as open `file-like` objects, and firebird-driver will handle the - transfer of BLOB value. - -Parametrized statemets also have some limitations. Currently: - -* `DATE`, `TIME` and `DATETIME` values must be relevant `datetime` objects. -* `NUMERIC` and `DECIMAL` values must be `decimal` objects. - -.. index:: - pair: SQL Statement; prepared - -.. _prepared-statements: - -Prepared Statements -------------------- - -Execution of any SQL statement has three phases: - -* *Preparation*: command is analyzed, validated, execution plan is determined - by optimizer and all necessary data structures (for example for input and output - parameters) are initialized. -* *Execution*: input parameters (if any) are passed to server and previously - prepared statement is actually executed by database engine. -* *Fetching*: result of execution and data (if any) are transferred from server - to client, and allocated resources are then released (by closing the statement). - -The preparation phase consumes some amount of server resources (memory and CPU). -Although preparation and release of resources typically takes only small amount -of CPU time, it builds up as number of executed statements grows. Firebird (like -most database engines) allows to spare this time for subsequent execution if -particular statement should be executed repeatedly - by reusing once prepared -statement for repeated execution. This may save significant amount of server -processing time, and result in better overall performance. - -Firebird-driver builds on this by encapsulating the Firebird SQL statement data -and related code into separate `.Statement` class, and implementing the `.Cursor` -class around it. The Cursor uses either an internally managed `.Statement` instance -to execute SQL commands provided as `string`, or uses `.Statement` instance -provided by your code as SQL command. - -To get the (prepared) `.Statement` instance for later (repeated) execution, use -`~.Cursor.prepare()` method. You can then pass this instance to `~.Cursor.execute()`, -`~.Cursor.executemany()` or `~.Cursor.open()` instead `command string`. - -`.Statement` instances are bound to `.Connection` instance, and can't be used -with any other `.Connection`. Beside repeated execution they are also useful -to get information about statement (like its execution `~.Statement.plan` or -`~.Statement.type`) before its execution. - -.. note:: - - The internally managed `.Statement` instance is released when `.Cursor` is closed, - or before any new statement is executed. It means that if your code executes - the same SQL command (passed as string) repeatedly without closing the cursor - between calls, the same `.Statement` instance is (re)used. - -.. important:: - - Implementation of Cursor in firebird-driver somewhat violates the Python DB API 2.0, - which requires that cursor will be unusable after call to `~.Cursor.close()`; and - an Error (or subclass) exception should be raised if any operation is attempted with - the cursor. In firebird-driver, the `.Cursor.close()` call only releases resources - associated with executed statement like the result set, and you can't fetch data or - query information about the SQL statement. However, you can use the cursor instance - to execute new SQL commands. - - .. warning:: - - If you'll take advantage of this anomaly, your code would be less portable to other - Python DB API 2.0 compliant drivers. - -**Example:** - -.. sourcecode:: python - - insertStatement = cur.prepare("insert into the_table (a,b,c) values (?,?,?)") - - inputRows = [ - ('aardvark', 1, 0.1), - ('zymurgy', 2147483647, 99999.999), - ('foobar', 2000, 9.9) - ] - - for row in inputRows: - cur.execute(insertStatement,row) - # - # or you can use executemany - # - cur.executemany(insertStatement, inputRows) - - -.. seealso:: `.Statement` for details. - -.. index:: - pair: Cursor; named - -Named Cursors -------------- - -To allow the Python programmer to perform scrolling **UPDATE** or **DELETE** via the -**“SELECT ... FOR UPDATE”** syntax, the firebird-driver provides the read-only property -`.Cursor.name` and method `.Cursor.set_cursor_name()`. - -**Example Program:** - -.. sourcecode:: python - - from firebird.driver import connect - - with connect('employee', user='sysdba', password='masterkey') as con: - curScroll = con.cursor() - curUpdate = con.cursor() - - curScroll.execute("select city from customer for update") - curScroll.set_cursor_name('city_scroller') - update = "update customer set city=? where current of " + curScroll.name - - for (city,) in curScroll: - city = ... # make some changes to city - curUpdate.execute( update, (city,) ) - - con.commit() - -.. index:: - pair: Stored procedure; execution - -Working with stored procedures ------------------------------- - -Firebird stored procedures can have input parameters and/or output parameters. -Some databases support input/output parameters, where the same parameter is used -for both input and output; Firebird does not support this. - -It is important to distinguish between procedures that **return a result set** and -procedures that **populate and return their output parameters** exactly once. Conceptually, -the latter “return their output parameters” like a Python function, whereas the former -“yield result rows” like a Python generator. - -Firebird’s **server-side** procedural SQL syntax makes no such distinction, but client-side -SQL code (and C API code) must. A result set is retrieved from a stored procedure by -**SELECT'ing from the procedure, whereas output parameters are retrieved with an -'EXECUTE PROCEDURE' statement**. - -To **retrieve a result set** from a stored procedure with firebird-driver, use code -such as this: - -.. sourcecode:: python - - cur.execute("select output1, output2 from the_proc(?, ?)", (input1, input2)) - - # Ordinary fetch code here, such as: - for row in cur: - ... # process row - - con.commit() # If the procedure had any side effects, commit them. - -To **execute** a stored procedure and **access its output parameters**, you can -choose from two options: - -1. Method `.Cursor.callproc()` that **conforms to Python DB API 2.0**. This method - does not returns the output parameters directly, and you must call `.Cursor.fetchone()` - **exactly once** to retrieve them. - -2. Method `.Cursor.call_procedure()` that returns output parameters directly - (or `None` if procedure does not have output parameters). - -**Examples:** - -.. sourcecode:: python - - # Python DB API 2.0 compliant method: - cur.callproc("the_proc", (input1, input2)) - # If there are output parameters, retrieve them as though they were the - # first row of a result set... - outputParams = cur.fetchone() - - # alternative method: - outputParams = cur.call_procedure("the_proc", (input1, input2)) - - con.commit() # If the procedure had any side effects, commit them. - - -.. index:: - pair: Data; conversion - -Data handling and conversions -============================= - -.. index:: - pair: parameter; conversion - -Implicit Conversion of Input Parameters from Strings ----------------------------------------------------- - -The Firebird database engine treats most SQL data types in a weakly typed fashion: -the engine may attempt to convert the raw value to a different type, as appropriate -for the current context. For instance, the SQL expressions `123` (integer) and `‘123’` -(string) are treated equivalently when the value is to be inserted into an `integer` -field; the same applies when `‘123’` and `123` are to be inserted into a `varchar` field. - -This weak typing model is quite unlike Python’s dynamic yet strong typing. Although -weak typing is regarded with suspicion by most experienced Python programmers, the -database engine is in certain situations so aggressive about its typing model that -firebird-driver must compromise in order to remain an elegant means of programming -the database engine. - -An example is the handling of “magic values” for date and time fields. The database -engine interprets certain string values such as `‘yesterday’` and `‘now’` as having -special meaning in a date/time context. If firebird-driver did not accept strings as -the values of parameters destined for storage in date/time fields, the resulting code -would be awkward. Consider the difference between the two Python snippets below, which -insert a row containing an integer and a timestamp into a table defined with the following -DDL statement: - -.. sourcecode:: sql - - create table test_table (i integer, t timestamp) - -.. sourcecode:: python - - i = 1 - t = 'now' - sqlWithMagicValues = f"insert into test_table (i, t) values (?, '{t}')" - cur.execute(sqlWithMagicValues, (i,)) - -.. sourcecode:: python - - i = 1 - t = 'now' - cur.execute("insert into test_table (i, t) values (?, ?)", (i, t)) - -If firebird-driver did not support weak parameter typing, string parameters that -the database engine is to interpret as “magic values” would have to be rolled into -the SQL statement in a separate operation from the binding of the rest of the parameters, -as in the first Python snippet above. Implicit conversion of parameter values from -strings allows the consistency evident in the second snippet, which is both more -readable and more general. - -.. note:: - - It should be noted that firebird-driver does not perform the conversion from string - itself. Instead, it passes that responsibility to the database engine by changing - the parameter metadata structure dynamically at the last moment, then restoring - the original state of the metadata structure after the database engine has performed - the conversion. - -A secondary benefit is that when one uses firebird-driver to import large amounts -of data from flat files into the database, the incoming values need not necessarily -be converted to their proper Python types before being passed to the database engine. -Eliminating this intermediate step may accelerate the import process considerably, -although other factors such as the chosen connection protocol and the deactivation -of indexes during the import are more consequential. For bulk import tasks, the -database engine’s external tables also deserve consideration. External tables can -be used to suck semi-structured data from flat files directly into the relational -database without the intervention of an ad hoc conversion program. - -.. index:: - pair: unicode; conversion - -Automatic conversion from/to Unicode ------------------------------------- - -In Firebird, every `CHAR`, `VARCHAR` or textual `BLOB` field can (or, better: must) -have a `character set` assigned. While it's possible to define single character set -for whole database, it's also possible to define different character set for each -textual field. This information is used to correctly store the bytes that make up -the character string, and together with collation information (that defines the sort -ordering and uppercase conversions for a string) is vital for correct data manipulation, -including automatic transliteration between character sets when necessary. - -.. important:: - - Because data also flow between server and client application, it's vital that client - will send data encoded only in character set(s) that server expects. While it's - possible to leave this responsibility completely on client application, it's better - when client and server settle on single character set they would use for communication, - especially when database operates with multiple character sets, or uses character set - that is not `native` for client application. - - Character set for communication is specified using `~.DatabaseConfig.charset` - configuration option, or parameter in `.connect()` or `~firebird.driver.core.create_database()` call. - - When `connection charset` is defined, all textual data returned from server are encoded - in this charset, and client application must ensure that all textual data sent to server - are encoded only in this charset as well. - -Firebird-driver helps with client side of this character set bargain by automatically -converting Python `str` values into `bytes` encoded in connection character set, -and vice versa. However, developers are still responsible that `bytes` strings -passed to server are in correct encoding (because firebird-driver makes no assumption -about encoding of `bytes` strings, so it can't recode them to connection charset). - -.. important:: - - In case that `connection charset` is NOT defined at all, or `NONE` charset is specified, - firebird-driver uses `locale.getpreferredencoding` to determine encoding for conversions - from/to `unicode`. - -.. important:: - - There is one exception to automatic conversion: when character set OCTETS is defined - for data column. Values assigned to OCTETS columns are always passed `as is`, because - they're basically binary streams. This has specific implications. Python 3 native - strings are `unicode`, and you would probably want to use `bytes` type instead. However, - firebird-driver in this case doesn't check the value type at all, so you'll not be - warned if you'll make a mistake and pass `str` to OCTETS column (unless you'll pass - more bytes than column may hold, or you intend to store unicode that way). - -Conversion is fully automatic in both directions for all textual data, i.e. including -for string values returned by Firebird Service and `info` calls etc. When `connection -charset` is not specified, firebird-driver uses `locale.getpreferredencoding` to -determine encoding for conversions from/to `unicode`. - -.. tip:: - - Except for legacy databases that doesn't have `character set` defined, **always** - define character set for your databases and specify `connection charset`. It will - make your life much easier. - -.. index:: BLOB - pair: Data; BLOB - pair: BLOB; materialized - pair: BLOB; stream - -.. _working_with_blobs: - -Working with TIME/TIMESTAMP WITH TIMEZONE ------------------------------------------ - -Firebird 4 introduced support for TIME and TIMESTAMP WITH TIMEZONE. The driver supports these -types with timezone-aware `datetime.datetime` and `datetime.time` objects. However, this -support has some specific limitations: - -1. The driver uses `python-dateutil` package to handle timezone information. Due to specific - requirements it's not possible to use standard `zoneinfo` package available in Python since - version 3.9, neither any other `datetime.tzinfo` implementation. -2. All timezone-aware `datetime.datetime` and `datetime.time` objects passed to the driver - must use `datetime.tzinfo` created with `.get_timezone()` utility function. - -**Examples:** - -.. sourcecode:: python - - from firebird.driver import get_timezone - - ts_region = datetime.datetime(2020, 12, 31, 23, 55, 35, 123400, get_timezone('Europe/Prague')) - ts_offset = datetime.datetime(2020, 12, 31, 23, 55, 35, 123400, get_timezone('+02:00')) - -Working with BLOBs ------------------- - -Firebird-driver uses two types of BLOB values: - -* **Materialized** BLOB values are Python `str` or `bytes` values. This is the **default** type. -* **Streamed** BLOB values are `file-like` objects. - -Materialized BLOBs are easy to work with, but are not suitable for: - -* **deferred loading** of BLOBs. They're called `materialized` because they're always - fetched from server as part of row fetch. Fetching BLOB value means separate API calls - (and network roundtrips), which may slow down you application considerably. -* **large values**, as they are always stored in memory in full size. - -These drawbacks are addressed by `stream` BLOBs. Using BLOBs in `stream` mode is easy: - -* For **input** values, simply use :ref:`parameterized statement ` - and pass any `file-like` object in place of BLOB parameter. The `file-like` object must - implement only the `~file.read` method, as no other method is used. -* For **output** values, add column name(s) that should be returned as `file-like` - objects to `.Cursor.stream_blobs` list attribute. Firebird-driver then returns - `.BlobReader` instance instead string in place of returned BLOB value for these column(s). - -.. important:: - - The firebird-driver provides `.Cursor.stream_blob_threshold` attribute that controls - the maximum size of materialized blobs (as memory exhaustion safeguard). When particular - blob value exceeds this threshold, an instance of `.BlobReader` is returned instead - string/bytes value. - - Zero threshold value effectively forces all blobs to be returned as stream blobs. - Negative value means no size limit for materialized blobs (use at your own risk). - Please note that positive threshold value means that your application has to be - prepared to handle BLOBs in both incarnations. - - The default threshold is 64K and could be changed using `.DriverConfig.stream_blob_threshold` - configuration option. - - Blob size threshold has effect only on materialized blob columns, i.e. columns not - explicitly requested to be returned as streamed ones using `.Cursor.stream_blobs` - attribute, that are **always** returned as stream blobs. - - -The `.BlobReader` instance is bound to `.Cursor` instance, and it's automatically closed -with cursor. However, it's good practice to use `with` statement or call `.BlobReader.close()` -once you're finished reading to release system resources associated with BLOB value. - -.. important:: - - When working with BLOB values, always have memory efficiency in mind, especially when - you're processing huge quantity of rows with BLOB values at once. Materialized BLOB - values may exhaust your memory quickly, but using stream BLOBs may have inpact on - performance too, as new `.BlobReader` instance is created for each value fetched. - -**Example program:** - -.. sourcecode:: python - - from firebird.driver import connect - - with connect('employee', user='SYSDBA', password='masterkey') as con: - cur = con.cursor() - print("Materialized retrieval (as str):") - cur.execute('select proj_id, proj_desc from project') - proj_id, proj_desc = cur.fetchone() - print(f"{proj_id=}, {proj_desc=}") - - print("\nStreaming retrieval (via BlobReader):") - cur.stream_blobs.append('PROJ_DESC') - cur.execute('select proj_id, proj_desc from project') - proj_id, proj_desc = cur.fetchone() - with proj_desc: - print(f"{proj_id=}, {proj_desc=}") - print(proj_desc.read()) - -Output:: - - Materialized retrieval (as str): - proj_id='VBASE', proj_desc='Design a video data base management system for\ncontrolling on-demand video distribution.\n' - - Streaming retrieval (via BlobReader): - proj_id='VBASE', proj_desc=BlobReader[size=89] - Design a video data base management system for - controlling on-demand video distribution. - -.. index:: ARRAY - pair: Data; ARRAY - -Firebird ARRAY type -------------------- - -Firebird-driver supports Firebird ARRAY data type. ARRAY values are represented as -Python lists. On input, the Python sequence (list or tuple) must be nested appropriately -if the array field is multi-dimensional, and the incoming sequence must not fall short -of its maximum possible length (it will not be “padded” implicitly–see below). On output, -the lists will be nested if the database array has multiple dimensions. - -.. note:: - - Database arrays have no place in a purely relational data model, which requires that - data values be atomized (that is, every value stored in the database must be reduced - to elementary, non-decomposable parts). The Firebird implementation of database arrays, - like that of most relational database engines that support this data type, is fraught - with limitations. - - Database arrays are of fixed size, with a predeclared number of dimensions (max. 16) - and number of elements per dimension. Individual array elements cannot be set to - NULL / None, so the mapping between Python lists (which have dynamic length and are - therefore not normally “padded” with dummy values) and non-trivial database arrays is - clumsy. - - Stored procedures cannot have array parameters. - - Finally, many interface libraries, GUIs, and even the isql command line utility do not - support database arrays. - - In general, it is preferable to avoid using database arrays unless you have a compelling - reason. - -**Example:** - -.. sourcecode:: python - - >>> from firebird.driver import connect - >>> con = connect('employee',user='sysdba', password='masterkey') - >>> cur = con.cursor() - >>> cur.execute("select LANGUAGE_REQ from job where job_code='Eng' and job_grade=3 and job_country='Japan'") - >>> cur.fetchone() - (['Japanese\n', 'Mandarin\n', 'English\n', '\n', '\n'],) - -**Example program:** - -.. sourcecode:: python - - from firebird.driver import connect - - arrayIn = [ - [1, 2, 3, 4], - [5, 6, 7, 8], - [9,10,11,12] - ] - - with connect('/temp/test.db', user='sysdba', password='pass') as con: - con.execute_immediate("recreate table array_table (a int[3,4])") - con.commit() - - cur = con.cursor() - - print(f"{arrayIn=}") - cur.execute("insert into array_table values (?)", (arrayIn,)) - con.commit() - - cur.execute("select a from array_table") - arrayOut = cur.fetchone()[0] - print(f"{arrayOut=}) - -Output:: - - arrayIn=[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] - arrayOut=[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] - -.. index:: - pair: Transaction; management - -Transanction management -======================= - -For the sake of simplicity, firebird-driver lets the Python programmer ignore -transaction management to the greatest extent allowed by the Python Database -API Specification 2.0. The specification says, “if the database supports an -auto-commit feature, this must be initially off”. At a minimum, therefore, -it is necessary to call the commit method of the connection in order to persist -any changes made to the database. - -Remember that because of ACID, every data manipulation operation in the Firebird -database engine takes place in the context of a transaction, including operations -that are conceptually “read-only”, such as a typical SELECT. The client programmer -of firebird-driver establishes a transaction implicitly by using any SQL execution -method, such as `.Connection.execute_immediate()`, `.Cursor.execute()`, or -`.Cursor.callproc()`. - -Although firebird-driver allows the programmer to pay little attention to transactions, -it also exposes the full complement of the database engine’s advanced transaction -control features: `transaction parameters`_, `retaining transactions`_, `savepoints`_, -and `distributed transactions`_. - -Basics ------- - -When it comes to transactions, Python Database API 2.0 specify that `.Connection` object -has to respond to the following methods: - -`.Connection.commit()` - - Commits any pending transaction to the database. Note that if the database supports - an auto-commit feature, this must be initially off. An interface method may be provided - to turn it back on. Database modules that do not support transactions should implement - this method with void functionality. - -`.Connection.rollback()` - - (optional) In case a database does provide transactions this method causes the the - database to roll back to the start of any pending transaction. **Closing a connection - without committing the changes first will cause an implicit rollback to be performed.** - -In addition to the implicit transaction initiation required by Python Database API, -firebird-driver allows the programmer to start transactions explicitly via the -`.Connection.begin()` method. Also `.Connection.savepoint()` method was added to provide -support for `Firebird SAVEPOINTs`_. - -But Python Database API 2.0 was created with assumption that connection can support only -one transactions per single connection. However, Firebird can support multiple independent -transactions that can run simultaneously within single connection / attachment to the -database. This feature is very important, as applications may require multiple transaction -opened simultaneously to perform various tasks, which would require to open multiple -connections and thus consume more resources than necessary. - -Firebird-driver surfaces this Firebird feature by separating transaction management out -from `.Connection` into separate `.TransactionManager` objects. To comply with Python DB -API 2.0 requirements, `.Connection` object uses one `.TransactionManager` instance as -:attr:`main transaction <.Connection.main_transaction>`, and delegates `~.Connection.begin()`, -`~.Connection.savepoint()`, `~.Connection.commit()`, `~.Connection.rollback()` and -`~.Connection.execute_immediate()` calls to it. - -.. seealso:: - - More about using multiple transactions with the same connection in separate - :ref:`section `. - -**Example:** - -.. sourcecode:: python - - from firebird.driver import connect - - with connect('employee', user='SYSDBA', password='masterkey') as con: - cur = con.cursor() - - # Most minimalistic transaction management -> implicit start, only commit() and rollback() - # ======================================================================================== - # - # Transaction is started implicitly - cur.execute('insert into country values ('Oz','Crowns') - con.commit() # commits active transaction - # Again, transaction is started implicitly - cur.execute('insert into country values ('Barsoom','XXX') - con.rollback() # rolls back active transaction - cur.execute('insert into country values ('Pellucidar','Shells') - - # Commit was not performed before connection context was closed - # This will roll back the transaction because Python DB API 2.0 - # requires that closing connection with pending transaction must - # cause an implicit rollback - -.. seealso:: `.TransactionManager` for details. - -.. index:: - pair: Transaction; auto-commit - -Auto-commit ------------ - -Firebird-driver doesn't support `auto-commit` feature directly, but developers -may achieve the similar result using `explicit` transaction start, taking advantage -of `.TransactionManager.default_action` and its default value (`~.DefaultAction.COMMIT`). - -**Example:** - -.. sourcecode:: python - - from firebird.driver import connect - - with connect('employee', user='SYSDBA', password='masterkey') as con: - cur = con.cursor() - - con.begin() - cur.execute('insert into country values ('Oz','Crowns') - con.begin() # commits active transaction and starts new one - cur.execute('insert into country values ('Barsoom','XXX') - con.begin() # commits active transaction and starts new one - cur.execute('insert into country values ('Pellucidar','Shells') - - # However, commit is required before connection is closed, - # because Python DB API 2.0 requires that closing connection - # with pending transaction must cause an implicit rollback - con.commit() - -.. index:: - pair: Transaction; parameters - -Transaction parameters ----------------------- - -The database engine offers the client programmer an optional facility called -`transaction parameter buffers` (TPBs) for tweaking the operating characteristics -of the transactions he initiates. These include characteristics such as whether -the transaction has read and write access to tables, or read-only access, and -whether or not other simultaneously active transactions can share table access -with the transaction. - -Transaction manager has `~.TransactionManager.default_tpb` attribute that can be -changed to set the default TPB to be used for all subsequent transactions started -by this manager. Also Connection have a `~.Connection.default_tpb` attribute, -but it's used to set the default TPB for all transactions managers subsequently -created for the connection (see `.Connection.transaction_manager()`). - -Alternatively, if the programmer only wants to set the TPB for a single transaction, -he can start a transaction explicitly via the `.Connection.begin()` or -`.TransactionManager.begin()` method and pass a TPB for that single transaction. - -The TPB is a `bytes` value constructed from various tags and binary values, as -defined by API. While you can construct the TPB manually, the firebird-driver -provides several convenient ways for TPB construction: - -1. The `.tpb()` function for simple TPBs. - -2. The `~firebird.driver.core.TPB` class for complex TPBs (including table reservation etc.). - -**Examples:** - -.. sourcecode:: python - - from firebird.driver import tpb, TPB, Isolation, TraAccessMode, TableShareMode, TableAccessMode - - # Use tpb() if isolation, timeout and access_mode parameters are enough for you - simple_tpb = tpb(Isolation.READ_COMMITTED_READ_CONSISTENCY,100,TraAccessMode.WRITE) - - # Use TPB if you want additional parameters than isolation, timeout and access_mode - my_tpb = TPB(isolation=Isolation.SNAPSHOT, - access_mode=TraAccessMode.WRITE, - lock_timeout=100, - no_auto_undo=True, - auto_commit=True, - ignore_limbo=True) - my_tpb.reserve_table('MY_TABLE', TableShareMode.PROTECTED, TableAccessMode.LOCK_WRITE) - complex_tpb = my_tpb.get_buffer() - -.. index:: - pair: Transaction; information about - -Getting information about transaction -------------------------------------- - -.. important:: - - Because the scope and type of transaction information depends on the version of the Firebird - server, this information is made available through a separate class - `.TransactionInfoProvider`. The `.TransactionManager.info` property provides access to - instance of `.TransactionInfoProvider` or it's **ancestor** class according to used - Firebird version. - -Although you may query the information directly from server using -`~.TransactionInfoProvider3.get_info()` method (that wraps the Firebird `ITransaction.getInfo()` -API call), the `.TransactionInfoProvider` object provides more convenient methods and properties -for obtaining specific information directly. - -**Example:** - -.. sourcecode:: python - - from firebird.driver import connect, driver_config - - driver_config.server_defaults.host.value = 'localhost' - with connect('employee', user='SYSDBA', password='masterkey') as con: - con.begin() - info = con.main_transaction.info - print(f"Transaction ID: {info.id}") - print(f"Database: {info.database}") - print(f"Isolation level: {info.isolation!s}") - print(f"Lock timeout: {info.lock_timeout}") - print(f"Is Read-Only: {info.is_read_only()}") - print(f"ID of Oldest Interesting Transaction: {info.oit}") - print(f"ID of Oldest Active Transaction: {info.oat}") - print(f"ID of Oldest Snapshot Transaction: {info.ost}") - -Output:: - - Transaction ID: 352 - Database: localhost:employee - Isolation level: Isolation.SNAPSHOT - Lock timeout: -1 - Is Read-Only: False - ID of Oldest Interesting Transaction: 350 - ID of Oldest Active Transaction: 352 - ID of Oldest Snapshot Transaction: 352 - -.. index:: - pair: Transaction; retaining - -Retaining transactions ----------------------- - -The `~.TransactionManager.commit()` and `~.TransactionManager.rollback()` methods -accept an optional boolean keyword parameter `retaining` (**default False**) to -indicate whether to recycle the transactional context of the transaction being resolved -by the method call. - -If retaining is `True`, the infrastructural support for the transaction active at -the time of the method call will be “retained” (efficiently and transparently recycled) -after the database server has committed or rolled back the conceptual transaction. - -.. important:: - - In code that commits or rolls back frequently in short amount of time (like in loop), - “retaining” the transaction may yield better performance. However, retaining transactions - must be used cautiously because they can interfere with the server’s ability to garbage - collect old record versions. For details about this issue, read the “Garbage” section of - `this document `_ by Ann Harrison. - - It's definitely no recommended to use retaining for all transactions, or retain the transaction - context indefinitely (you should eventually commit/rollback the transaction in normal - way). - -For more information about retaining transactions, see `Firebird documentation`. - -.. index:: SAVEPOINT - pair: Transaction; SAVEPOINT - -Savepoints ----------- - -Savepoints are named, intermediate control points within an open transaction that -can later be rolled back to, without affecting the preceding work. Multiple savepoints -can exist within a single unresolved transaction, providing “multi-level undo” functionality. - -Although Firebird savepoints are fully supported from SQL alone via the `SAVEPOINT ‘name’` -and `ROLLBACK TO ‘name’` statements, firebird-driver also exposes savepoints at the Python -API level for the sake of convenience. - -Call to method `.TransactionManager.savepoint()` establishes a savepoint with the specified -`name`. To roll back to a specific savepoint, call the `~.TransactionManager.rollback()` -method and provide the name of the savepoint for the `savepoint` keyword parameter. If the -savepoint parameter of `~.TransactionManager.rollback()` is not specified, the active -transaction is cancelled in its entirety, as required by the Python Database API Specification. - -The following program demonstrates savepoint manipulation via the firebird-driver API, -rather than raw SQL. - -.. sourcecode:: python - - from firebird.driver import connect - - with connect('employee', user='SYSDBA', password='masterkey') as con: - cur = con.cursor() - - cur.execute("recreate table test_savepoints (a integer)") - con.commit() - - print('Before the first savepoint, the contents of the table are:') - cur.execute("select * from test_savepoints") - print(' ', cur.fetchall()) - - cur.execute("insert into test_savepoints values (?)", [1]) - con.savepoint('A') - print('After savepoint A, the contents of the table are:') - cur.execute("select * from test_savepoints") - print(' ', cur.fetchall()) - - cur.execute("insert into test_savepoints values (?)", [2]) - con.savepoint('B') - print('After savepoint B, the contents of the table are:') - cur.execute("select * from test_savepoints") - print(' ', cur.fetchall()) - - cur.execute("insert into test_savepoints values (?)", [3]) - con.savepoint('C') - print('After savepoint C, the contents of the table are:') - cur.execute("select * from test_savepoints") - print(' ', cur.fetchall()) - - con.rollback(savepoint='B') - print('After rolling back to savepoint B, the contents of the table are:') - cur.execute("select * from test_savepoints") - print(' ', cur.fetchall()) - - con.rollback() - print('After rolling back entirely, the contents of the table are:') - cur.execute("select * from test_savepoints") - print(' ', cur.fetchall()) - -The output of the example program is shown below:: - - Before the first savepoint, the contents of the table are: - [] - After savepoint A, the contents of the table are: - [(1,)] - After savepoint B, the contents of the table are: - [(1,), (2,)] - After savepoint C, the contents of the table are: - [(1,), (2,), (3,)] - After rolling back to savepoint B, the contents of the table are: - [(1,), (2,)] - After rolling back entirely, the contents of the table are: - [] - -.. index:: - pair: Transaction; multiple - -.. _multiple_transactions: - -Using multiple transactions with the same connection ----------------------------------------------------- - -To use additional transactions that could run simultaneously with -:attr:`main transaction <.Connection.main_transaction>` managed by `.Connection`, -create new `.TransactionManager` object calling `.Connection.transaction_manager()` -method. If you don't specify the optional `default_tpb` parameter, this new -`.TransactionManager` inherits the `~.Connection.default_tpb` from `.Connection`. -Physical transaction is not started when `.TransactionManager` instance is -created, but implicitly when first SQL statement for cursor created from -this manager is executed, or explicitly via `.TransactionManager.begin()` call. - -To execute statements in context of this additional transaction you have to -use `cursors` obtained directly from this `.TransactionManager` instance calling -its `~.TransactionManager.cursor()` method, or call `.TransactionManager.execute_immediate()` -method. - -**Example:** - -.. sourcecode:: python - - from firebird.driver import connect, tpb, Isolation, TraAccessMode - - with connect('employee', user='SYSDBA', password='masterkey') as con: - # Cursor for main_transaction context - cur = con.cursor() - - # Create new READ ONLY READ COMMITTED transaction - ro_transaction = con.transaction_manager(tpb(Isolation.READ_COMMITTED_RECORD_VERSION, - access=TraAccessMode.READ)) - # and cursor - ro_cur = ro_transaction.cursor() - - cur.execute('insert into country values ('Oz','Crowns') - con.commit() # commits main transaction - - # Read data created by main transaction from second one - ro_cur.execute("select * from COUNTRY where COUNTRY = `Oz`") - print(ro_cur.fetchall()) - - # Insert more data, but don't commit - cur.execute('insert into country values ('Barsoom','XXX') - - # Read data created by main transaction from second one - ro_cur.execute("select * from COUNTRY where COUNTRY = `Barsoom`") - print(ro_cur.fetchall()) - -.. index:: - pair: Transaction; distributed - -.. _distributed_transactions: - -Distributed Transactions ------------------------- - -Distributed transactions are transactions that span multiple databases. -Firebird-driver provides this Firebird feature through `.DistributedTransactionManager` -class. Instances of this class must be created manually, and managed transactions -are fully independent from all other transactions, main or secondary, of member connections. - -Similarly to `.TransactionManager`, distributed transactions are managed -through `~.DistributedTransactionManager.begin()`, -`~.DistributedTransactionManager.savepoint()`, `~.DistributedTransactionManager.commit()` -and `~.DistributedTransactionManager.rollback()` methods. -Additionally, `.DistributedTransactionManager` exposes method -`~.DistributedTransactionManager.prepare()` that explicitly initiates the -first phase of `Two-Phase Commit Protocol`. Transaction parameters are defined -similarly to `.TransactionManager` using `~.DistributedTransactionManager.default_tpb` -or as optional parameter to `~.DistributedTransactionManager.begin()` call. - -SQL statements that should belong to context of distributed transaction are -executed via `.Cursor` instances aquired through `.DistributedTransactionManager.cursor()` -method, or calling `.DistributedTransactionManager.execute_immediate()` method. - -.. note:: - - Because `.Cursor` instances can belong to only one `.Connection`, the - `~.DistributedTransactionManager.cursor()` method has mandatory parameter - `connection`, to specify to which member connection cursor should belong. - - The `~.DistributedTransactionManager.execute_immediate()` method operates - on **all** databases in *group*. - -**Example program:** - -.. sourcecode:: python - - from firebird.driver import create_database, DistributedTransactionManager - - # First database - con1 = create_database('db1.fdb', user='SYSDBA', password='masterkey') - con1.execute_immediate("recreate table T (PK integer, C1 integer)") - con1.commit() - - # Second database - con2 = create_database('db2.fdb', user='SYSDBA', password='masterkey') - con2.execute_immediate("recreate table T (PK integer, C1 integer)") - con2.commit() - - # Create distributed transaction manager - dt = DistributedTransactionManager((con1,con2)) - - # Prepare cursors for each connection - dc1 = dt.cursor(con1) - dc2 = dt.cursor(con2) - - # Connection cursors to check content of databases - q = 'select * from T order by pk' - - cc1 = con1.cursor() - p1 = cc1.prep(q) - - cc2 = con2.cursor() - p2 = cc2.prep(q) - - print("Distributed transaction: COMMIT") - # =============================== - dc1.execute('insert into t (pk) values (1)') - dc2.execute('insert into t (pk) values (1)') - dt.commit() - - # check it - con1.commit() - cc1.execute(p1) - print('db1:', cc1.fetchall()) - con2.commit() - cc2.execute(p2) - print('db2:', cc2.fetchall()) - - print("Distributed transaction: PREPARE + COMMIT") - # ========================================= - dc1.execute('insert into t (pk) values (2)') - dc2.execute('insert into t (pk) values (2)') - dt.prepare() - dt.commit() - - # check it - con1.commit() - cc1.execute(p1) - print('db1:', cc1.fetchall()) - con2.commit() - cc2.execute(p2) - print('db2:', cc2.fetchall()) - - print("Distributed transaction: SAVEPOINT + ROLLBACK to it") - # =================================================== - dc1.execute('insert into t (pk) values (3)') - dt.savepoint('CG_SAVEPOINT') - dc2.execute('insert into t (pk) values (3)') - dt.rollback(savepoint='CG_SAVEPOINT') - - # check it - via group cursors, as transaction is still active - dc1.execute(q) - print('db1:', dc1.fetchall()) - dc2.execute(q) - print('db2:', dc2.fetchall()) - - print("Distributed transaction: ROLLBACK") - # ================================= - dt.rollback() - - # check it - con1.commit() - cc1.execute(p1) - print('db1:', cc1.fetchall()) - con2.commit() - cc2.execute(p2) - print('db2:', cc2.fetchall()) - - print("Distributed transaction: EXECUTE_IMMEDIATE") - # ========================================== - dt.execute_immediate('insert into t (pk) values (3)') - dt.commit() - - # check it - con1.commit() - cc1.execute(p1) - print('db1:', cc1.fetchall()) - con2.commit() - cc2.execute(p2) - print('db2:', cc2.fetchall()) - - # Finalize - con1.drop_database() - con1.close() - con2.drop_database() - con2.close() - -Output:: - - Distributed transaction: COMMIT - db1: [(1, None)] - db2: [(1, None)] - Distributed transaction: PREPARE + COMMIT - db1: [(1, None), (2, None)] - db2: [(1, None), (2, None)] - Distributed transaction: SAVEPOINT + ROLLBACK to it - db1: [(1, None), (2, None), (3, None)] - db2: [(1, None), (2, None)] - Distributed transaction: ROLLBACK - db1: [(1, None), (2, None)] - db2: [(1, None), (2, None)] - Distributed transaction: EXECUTE_IMMEDIATE - db1: [(1, None), (2, None), (3, None)] - db2: [(1, None), (2, None), (3, None)] - -.. index:: - pair: Transaction; context manager - -.. _transaction-context-manager: - -Transaction Context Manager ---------------------------- - -Firebird-driver provides context manager `~firebird.driver.core.transaction` that allows automatic -transaction management using :ref:`WITH statement `. It can work with -any object that supports `begin()`, `commit()` and `rollback()` methods, i.e. -`.Connection`, `.TransactionManager` or `.DistributedTransactionManager`. - -It starts transaction when WITH block is entered and commits it if no exception -occurs within it, or calls `rollback()` otherwise. Exceptions raised in WITH -block are never suppressed. - -Examples: - -.. sourcecode:: python - - from firebird.driver import connect, transaction, DistributedTransactionManager - - with connect('employee', user='SYSDBA', password='masterkey') as con: - - # Uses default main transaction - with transaction(con): - cur = con.cursor() - cur.execute("insert into T (PK,C1) values (1,'TXT')") - - # Uses separate transaction - with transaction(con.transaction_manager()) as tr: - cur = tr.cursor() - cur.execute("insert into T (PK,C1) values (2,'AAA')") - - # Uses distributed transaction - with connect('employee2', user='SYSDBA', password='masterkey') as con2, - DistributedTransactionManager(con, con2) as dtm: - with transaction(dtm): - cur1 = cg.cursor(con) - cur2 = cg.cursor(con2) - cur1.execute("insert into T (PK,C1) values (3,'Local')") - cur2.execute("insert into T (PK,C1) values (3,'Remote')") - -.. index:: - pair: Database; events - -Database Events -=============== - -What they are -------------- -The Firebird engine features a distributed, inter-process communication mechanism based on -messages called `database events`. A database event is a message passed from a trigger or -stored procedure to an application to announce the occurrence of a specified condition or -action, usually a database change such as an insertion, modification, or deletion of a record. -The Firebird event mechanism enables applications to respond to actions and database changes -made by other, concurrently running applications without the need for those applications to -communicate directly with one another, and without incurring the expense of CPU time -required for periodic polling to determine if an event has occurred. - -Why use them ------------- -Anything that can be accomplished with database events can also be implemented using other -techniques, so why bother with events? Since you’ve chosen to write database-centric programs -in Python rather than assembly language, you probably already know the answer to this question, -but let’s illustrate. - -A typical application for database events is the handling of administrative messages. -Suppose you have an administrative message database with a `message's` table, into which -various applications insert timestamped status reports. It may be desirable to react to -these messages in diverse ways, depending on the status they indicate: to ignore them, to -initiate the update of dependent databases upon their arrival, to forward them by e-mail -to a remote administrator, or even to set off an alarm so that on-site administrators will -know a problem has occurred. - -It is undesirable to tightly couple the program whose status is being reported -(the `message producer`) to the program that handles the status reports (the `message handler`). -There are obvious losses of flexibility in doing so. For example, the message producer may -run on a separate machine from the administrative message database and may lack access rights -to the downstream reporting facilities (e.g., network access to the SMTP server, in the case -of forwarded e-mail notifications). Additionally, the actions required to handle status -reports may themselves be time-consuming and error-prone, as in accessing a remote network -to transmit e-mail. - -In the absence of database event support, the message handler would probably be implemented -via `polling`. Polling is simply the repetition of a check for a condition at a specified -interval. In this case, the message handler would check in an infinite loop to see whether -the most recent record in the `messages` table was more recent than the last message it had -handled. If so, it would handle the fresh message(s); if not, it would go to sleep for -a specified interval, then loop. - -The `polling-based` implementation of the message handler is fundamentally flawed. Polling -is a form of busy-wait_; the check for new messages is performed at the specified interval, -regardless of the actual activity level of the message producers. If the polling interval -is lengthy, messages might not be handled within a reasonable time period after their arrival; -if the polling interval is brief, the message handler program (and there may be many such -programs) will waste a large amount of CPU time on unnecessary checks. - -The database server is necessarily aware of the exact moment when a new message arrives. -Why not let the message handler program request that the database server send it a notification -when a new message arrives? The message handler can then efficiently sleep until the moment -its services are needed. Under this `event-based` scheme, the message handler becomes -aware of new messages at the instant they arrive, yet it does not waste CPU time checking -in vain for new messages when there are none available. - -How events are exposed ----------------------- - -#. Server Process ("An event just occurred!") - - To notify any interested listeners that a specific event has - occurred, issue the `POST_EVENT` statement from Stored Procedure - or Trigger. The `POST_EVENT` statement has one parameter: the name - of the event to post. In the preceding example of the administrative - message database, `POST_EVENT` might be used from an `after insert` - trigger on the `messages` table, like this: - - .. sourcecode:: sql - - create trigger trig_messages_handle_insert - for messages - after insert - as - begin - POST_EVENT 'new_message'; - end - - .. note:: The physical notification of the client process does not - occur until the transaction in which the `POST_EVENT` took place is - actually committed. Therefore, multiple events may *conceptually* - occur before the client process is *physically* informed of even one - occurrence. Furthermore, the database engine makes no guarantee that - clients will be informed of events in the same groupings in which they - conceptually occurred. If, within a single transaction, an event named - `event_a` is posted once and an event named `event_b` is posted once, - the client may receive those posts in separate "batches", despite the - fact that they occurred in the same conceptual unit (a single - transaction). This also applies to multiple occurrences of *the same* - event within a single conceptual unit: the physical notifications may - arrive at the client separately. - -#. Client Process ("Send me a message when an event occurs.") - - .. note:: If you don't care about the gory details of event notification, - skip to the section that describes FDB's Python-level event handling - API. - - The Firebird C client library offers two forms of event notification. - The first form is *synchronous* notification, by way of the function - :c:func:`isc_wait_for_event()`. This form is admirably simple for a C programmer - to use, but is inappropriate as a basis for FDB's event support, - chiefly because it's not sophisticated enough to serve as the basis for - a comfortable Python-level API. The other form of event notification - offered by the database client library is *asynchronous*, by way of the - functions :c:func:`isc_que_events()` (note that the name of that function - is misspelled), :c:func:`isc_cancel_events()`, and others. The details are - as nasty as they are numerous, but the essence of using asynchronous - notification from C is as follows: - - #. Call :c:func:`isc_event_block()` to create a formatted binary buffer that will tell - the server which events the client wants to listen for. - #. Call :c:func:`isc_que_events()` (passing the buffer created in the previous step) to - inform the server that the client is ready to receive event notifications, and provide - a callback that will be asynchronously invoked when one or more of the registered events occurs. - #. [The thread that called :c:func:`isc_que_events()` to initiate event listening must - now do something else.] - #. When the callback is invoked (the database client library starts a thread dedicated - to this purpose), it can use the :c:func:`isc_event_counts()` function to determine - how many times each of the registered events has occurred since the last call to - :c:func:`isc_event_counts()` (if any). - #. [The callback thread should now "do its thing", which may include communicating with - the thread that called :c:func:`isc_que_events()`.] - #. When the callback thread is finished handling an event notification, it must call - :c:func:`isc_que_events()` again in order to receive future notifications. Future - notifications will invoke the callback again, effectively "looping" the callback - thread back to Step 4. - -API for Python developers -------------------------- - -The Firebird-driver database event API is comprised of the following: the method -`.Connection.event_collector()` and the class `.EventCollector`. - -Use the `.Connection.event_collector()` method (takes a sequence of string event -names as parameter) to create `.EventCollector` instance, that collects database event -notifications sent from the server for given database. - -.. important:: - - To start listening for events it's necessary to call `.EventCollector.begin()` - method or use EventCollector's context manager interface. - -Immediately when `~.EventCollector.begin()` method is called, EventCollector starts -to accumulate notifications of any event that occur within the collector’s internal queue -until the collector is closed either explicitly (via the `~.EventCollector.close()` -method) or implicitly (via garbage collection). - -Notifications about events are aquired through call to `~.EventCollector.wait()` method, -that blocks the calling thread until at least one of the events occurs, or the specified -`timeout` (if any) expires, and returns `None` if the wait timed out, or a dictionary that -maps `event_name -> event_occurrence_count`. - -.. important:: - - `.EventCollector` can act as context manager that ensures execution of - `~.EventCollector.begin()` and `~.EventCollector.close()` methods. - It's strongly advised to use the `.EventCollector` with the `with` statement. - -**Example:** - -.. sourcecode:: python - - with connection.event_collector(['event_a', 'event_b']) as collector: - events = collector.wait() - process_events(events) - -If you want to drop notifications accumulated so far by conduit, call -`.EventCollector.flush()` method. - -**Example program:** - -.. sourcecode:: python - - from firebird.driver import create_database, transaction - import threading - import time - - # Prepare database - con = create_database('event-test', user='SYSDBA', password='masterkey') - with transaction(con): - con.execute_immediate("CREATE TABLE T (PK Integer, C1 Integer)") - con.execute_immediate("""CREATE TRIGGER EVENTS_AU FOR T ACTIVE - BEFORE UPDATE POSITION 0 - AS - BEGIN - if (old.C1 <> new.C1) then - post_event 'c1_updated' ; - END""") - con.execute_immediate("""CREATE TRIGGER EVENTS_AI FOR T ACTIVE - AFTER INSERT POSITION 0 - AS - BEGIN - if (new.c1 = 1) then - post_event 'insert_1' ; - else if (new.c1 = 2) then - post_event 'insert_2' ; - else if (new.c1 = 3) then - post_event 'insert_3' ; - else - post_event 'insert_other' ; - END""") - cur = con.cursor() - - # Utility function - def send_events(command_list): - with transaction(con): - for cmd in command_list: - cur.execute(cmd) - - print("One event") - # ========= - timed_event = threading.Timer(3.0,send_events,args=[["insert into T (PK,C1) values (1,1)",]]) - with con.event_collector(['insert_1']) as events: - timed_event.start() - e = events.wait() - print(e) - - print("Multiple events") - # =============== - cmds = ["insert into T (PK,C1) values (1,1)", - "insert into T (PK,C1) values (1,2)", - "insert into T (PK,C1) values (1,3)", - "insert into T (PK,C1) values (1,1)", - "insert into T (PK,C1) values (1,2)",] - timed_event = threading.Timer(3.0,send_events,args=[cmds]) - with con.event_collector(['insert_1','insert_3']) as events: - timed_event.start() - e = events.wait() - print(e) - - print("20 events") - # ========= - cmds = ["insert into T (PK,C1) values (1,1)", - "insert into T (PK,C1) values (1,2)", - "insert into T (PK,C1) values (1,3)", - "insert into T (PK,C1) values (1,1)", - "insert into T (PK,C1) values (1,2)",] - timed_event = threading.Timer(1.0,send_events,args=[cmds]) - with con.event_collector(['insert_1','A','B','C','D', - 'E','F','G','H','I','J','K','L','M', - 'N','O','P','Q','R','insert_3']) as events: - timed_event.start() - time.sleep(3) - e = events.wait() - print(e) - - print("Flush events") - # ============ - timed_event = threading.Timer(3.0,send_events,args=[["insert into T (PK,C1) values (1,1)",]]) - with con.event_collector(['insert_1']) as events: - send_events(["insert into T (PK,C1) values (1,1)", - "insert into T (PK,C1) values (1,1)"]) - time.sleep(2) - events.flush() - timed_event.start() - e = events.wait() - print(e) - - # Finalize - con.drop_database() - con.close() - -Output:: - - One event - {'insert_1': 1} - Multiple events - {'insert_3': 1, 'insert_1': 2} - 20 events - {'A': 0, 'C': 0, 'B': 0, 'E': 0, 'D': 0, 'G': 0, 'insert_1': 2, 'I': 0, 'H': 0, 'K': 0, 'J': 0, 'M': 0, - 'L': 0, 'O': 0, 'N': 0, 'Q': 0, 'P': 0, 'R': 0, 'insert_3': 1, 'F': 0} - Flush events - {'insert_1': 1} - -.. index:: Services - pair: Services; working with - -.. index:: Server - pair: Server; services - -.. _working_with_services: - -Working with Services -===================== - -Database server maintenance tasks such as user management, load monitoring, -and database backup have traditionally been automated by scripting the -command-line tools :program:`gbak`, :program:`gfix`, :program:`gsec`, and :program:`gstat`. - -The API presented to the client programmer by these utilities is inelegant -because they are, after all, command-line tools rather than native components -of the client language. To address this problem, Firebird has a facility called -the `Services API`, which exposes a uniform interface to the administrative -functionality of the traditional command-line tools. - -The native Services API, though consistent, is much lower-level than a Pythonic API. -If the native version were exposed directly, accomplishing a given task would probably -require more Python code than scripting the traditional command-line tools. For this -reason, the firebird-driver presents its own abstraction over the native API. - -.. index:: - pair: Services; connection - pair: Server; connection - -Services API Connections ------------------------- - -All Services API operations are performed in the context of a `connection` to a specific -database server, represented by the `.Server` class. Similarly to database connections, -firebird-driver provides `.connect_server()` constructor function to create such connections. - -This constructor has one positional and several keyword parameters. - -The value of `server` positional parameter must be one of: - -* name of registered server configuration -* server host name or address - -Keyword parameters are intended to override selected configuration options, or to specify -options that are not configurable. - -A simple server connection is typically established with code such as this: - -.. sourcecode:: python - - from firebird.driver import connect_server - - # Attach to 'embedded' server - srv = connect_server('', user='SYSDBA', password='masterkey') - - # Attach to 'local' server - srv = connect_server('localhost', user='SYSDBA', password='masterkey') - - # Set 'user' and 'password' via configuration - from firebird.driver import driver_config - driver_config.server_defaults.user.value = 'SYSDBA' - driver_config.server_defaults.password.value = 'masterkey' - srv = connect_server('localhost') - -However, it's recommended to use specific configuration for servers. -It's possible to register servers directly in code like this: - -.. sourcecode:: python - - from firebird.driver import connect_server, driver_config - - # Register Firebird server - srv_cfg = """[main_server] - host = 192.168.0.15 - user = SYSDBA - password = Xyzzy - """ - driver_config.register_server('main_server', srv_cfg) - - # Attach to 'main' server - con = connect('main_server') - -But more convenient approach is using single configuration file:: - - # file: myapp.cfg - - [firebird.driver] - servers = main_server - databases = employee - - [main_server] - host = 192.168.0.15 - user = SYSDBA - password = Xyzzy - -.. sourcecode:: python - - from firebird.driver import connect_server, driver_config - - driver_config.read('myapp.cfg') - - # Attach to 'main' server - con = connect('main_server') - -.. note:: - - Like database connections, it's important to properly `~Server.close()` them - when you don't need them anymore. - -`.Server` object provides main infrastructure for communication with Firebird server services, -and manages number of objects that provide actual server services: - -* The `.Server.info` property object provides `Server Configuration and State information`_. -* The `.Server.database` property object provides `Database options`_ and `Database maintenance`_. -* The `.Server.user` property object provides `User maintenance`_. -* The `.Server.trace` property object provides management of `Trace sessions`_. - -.. seealso:: `.connect_server()` and `.Server` for details. - -.. index:: - pair: Services; output - -Text output from Services -------------------------- - -Some services like `.ServerDbServices.backup()` may return significant amount of text. -Rather than return the whole text as single string value by methods that provide access -to these services, firebird-driver isolated the transfer process to separate methods: - -* `~.Server.readline()` - Similar to `file.readline`, returns next line of output from Service. -* `~.Server.readline_timed()` - Like `~.Server.readline()` but with timeout. -* `~.Server.readlines()` - Like `file.readlines`, returns list of output lines. -* Iteration over `.Server` object, because `.Server` has built-in support for :ref:`iterator protocol `. -* Using `callback` method provided by developer. Each `.Server` method that returns its result - asynchronously accepts an optional parameter `callback`, which must be a function that accepts - one string parameter. This method is then called with each output line coming from service. -* `~.Server.wait()` - Waits for Sevice to finish, ignoring rest of the output it may produce. - -.. important:: - - The Firebird server sends text output from services as packets, that could have two forms. - The method for packet construction used for text transfer is controlled by `.Server.mode` - attribute with next possible values: - - 1. `.SrvInfoCode.LINE` : A single line of text. - 2. `.SrvInfoCode.TO_EOF` : A block of text up to specified (buffer) size. - - Both methods have specific pros and cons: - - 1. `~.SrvInfoCode.LINE` means more roundtrips and thus slower transfer of service output, - but each line is sent to client immediately when it's available. - 2. `~.SrvInfoCode.TO_EOF` means fewer roundtrips so large output is transferred quickly, - but service output is not sent until the transfer buffer is not full, or service stops. - - **The default mode is** `~.SrvInfoCode.TO_EOF` **with 64K buffer.** - -.. warning:: - - Until output is not fully fetched from service, any attempt to start another asynchronous - service will fail with exception! This constraint is set by Firebird Service API. - - You may check the status of asynchronous Services using `.Server.is_running()` method. - - In cases when you're not interested in output produced by Service, call `~.Server.wait()` - to wait for service to complete. - -.. important:: - - Normally, requesting output with `~.Server.readline()` blocks until any output is - available from server. Bacuse this method is used by iteration over `.Server` and - `~.Server.readlines()` method, they will block as well. Most services produce output - continuously and without (much) delay, so this is usually not a problem. However, some - services (eg trace) can produce output at significantly slower intervals (if at all), - which complicates the creation of responsive applications. In this case, it is necessary - to use the `~.Server.readline_timed()` method, which allows you to limit the waiting - time for the output. - -**Examples:** - -.. sourcecode:: python - - from firebird.driver import connect_server - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - print("Fetch materialized") - print("==================") - print("Start backup") - srv.database.backup(database='employee', backup='employee.fbk') - print("srv.running is", srv.isrunning()) - report = srv.readlines() - print(f"{len(report)} lines returned") - print("First 5 lines from output:") - for i in xrange(5): - print(i,report[i]) - print("srv.running is", srv.isrunning()) - print() - print("Iterate over result") - print("===================") - srv.database.backup(database='employee', backup='employee.fbk') - output = [] - for line in srv: - output.append(line) - print(f"{len(output)} lines returned") - print("Last 5 lines from output:") - for line in output[-5:]: - print(line) - print() - print("Callback") - print("========") - - output = [] - - # Callback function - def fetchline(line): - output.append(line) - - srv.database.backup(database='employee', backup='employee.fbk', callback=fetchline) - print(f"{len(output)} lines returned") - print("Last 5 lines from output:") - for line in output[-5:]: - print(line) - -Output:: - - Fetch materialized - ================== - Start backup - svc.running is True - 558 lines returned - First 5 lines from output: - 0 gbak:readied database employee for backup - 1 gbak:creating file employee.fbk - 2 gbak:starting transaction - 3 gbak:database employee has a page size of 4096 bytes. - 4 gbak:writing domains - svc.running is False - - Iterate over result - =================== - 558 lines returned - Last 5 lines from output: - gbak:writing referential constraints - gbak:writing check constraints - gbak:writing SQL roles - gbak:writing names mapping - gbak:closing file, committing, and finishing. 74752 bytes written - - Callback - ======== - 558 lines returned - Last 5 lines from output: - gbak:writing referential constraints - gbak:writing check constraints - gbak:writing SQL roles - gbak:writing names mapping - gbak:closing file, committing, and finishing. 74752 bytes written - -.. index:: - pair: Services; server information - -Server Configuration and State information ------------------------------------------- - -.. important:: - - Because the scope and type of service information depends on the version of the Firebird - server, this information is made available through a separate class - `.ServerInfoProvider`. The `.Server.info` property provides access to - instance of `.ServerInfoProvider` or it's **ancestor** class according to attached - Firebird server version. - - -`.ServerInfoProvider` methods and properties: - -* `~.ServerInfoProvider.get_log()` - Request the contents of the server’s log file (:file:`firebird.log`). - - This method is so-called `Async service` that only initiates log transfer. Actual log - content could be read by one from many methods for `text output from Services`_ that - `.Server` provides . - -* `~.ServerInfoProvider.version` - Returns Firebird server version as SEMVER string. - -* `~.ServerInfoProvider.engine_version` - Firebird server version as . float value. - -* `~.ServerInfoProvider.manager_version` - Firebird service manager version. - -* `~.ServerInfoProvider.architecture` - Firebird server implementation description. - -* `~.ServerInfoProvider.home_directory` - Firebird server home directory. - -* `~.ServerInfoProvider.security_database` - Security database. - -* `~.ServerInfoProvider.lock_directory` - Directory with lock file(s). - -* `~.ServerInfoProvider.message_directory` - Directory with message file(s). - -* `~.ServerInfoProvider.capabilities` - Firebird server capabilities (as `.ServerCapability` flags). - -* `~.ServerInfoProvider.connection_count` - Current number of database attachments. - -* `~.ServerInfoProvider.attached_databases` - List of attached databases. - -**Example:** - -.. sourcecode:: python - - from firebird.driver import driver_config, connect, connect_server - - srv_cfg = """[local] - host = localhost - user = SYSDBA - password = masterkey - """ - driver_config.register_server('local', srv_cfg) - db_cfg = """[employee] - server = local - database = employee.fdb - protocol = inet - """ - driver_config.register_database('employee', db_cfg) - with connect('employee', user='SYSDBA', password='masterkey'), connect_server('local', user='SYSDBA', password='masterkey') as srv: - print(f'{srv.info.version=}') - print(f'{srv.info.engine_version=}') - print(f'{srv.info.manager_version=}') - print(f'{srv.info.architecture=}') - print(f'{srv.info.home_directory=}') - print(f'{srv.info.security_database=}') - print(f'{srv.info.lock_directory=}') - print(f'{srv.info.message_directory=}') - print(f'{srv.info.capabilities=!s}') - print(f'{srv.info.connection_count=}') - print(f'{srv.info.attached_databases=}') - -Sample output for 64-bit Linux Firebird 4.0 Beta 2:: - - srv.info.version='4.0.0.1963' - srv.info.engine_version=4.0 - srv.info.manager_version=2 - srv.info.architecture='Firebird/Linux/AMD/Intel/x64' - srv.info.home_directory='/opt/firebird/' - srv.info.security_database='/opt/firebird/security4.fdb' - srv.info.lock_directory='/tmp/firebird/' - srv.info.message_directory='/opt/firebird/' - srv.info.capabilities=ServerCapability.REMOTE_HOP|MULTI_CLIENT - srv.info.connection_count=1 - srv.info.attached_databases=['/opt/firebird/examples/empbuild/employee.fdb'] - -.. index:: - pair: Services; database options - -Database options ----------------- - -Database options could be set using `.ServerDbServices` instance accessible via -`.Server.database` property. - -* `~.ServerDbServices.set_default_cache_size()` - Sets individual page cache size for database. - - .. sourcecode:: python - - >>> from firebird.driver import connect_server - >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - >>> srv.database.set_default_cache_size(database='employee.fdb', size=5000) - -* `~.ServerDbServices.set_sweep_interval()` - Sets database sweep interval. - - .. sourcecode:: python - - >>> from firebird.driver import connect_server - >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - >>> srv.database.set_sweep_interval(database='employee.fdb', interval=100000) - -* `~.ServerDbServices.set_space_reservation()` - Sets space reservation option for database. - - .. sourcecode:: python - - >>> from firebird.driver import connect_server, DbSpaceReservation - >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - >>> srv.database.set_space_reservation(database='employee.fdb', mode=DbSpaceReservation.USE_FULL) - -* `~.ServerDbServices.set_write_mode()` - Sets database write mode (SYNC/ASYNC). - - .. sourcecode:: python - - >>> from firebird.driver import connect_server, DbWriteMode - >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - >>> srv.database.set_write_mode(database='employee.fdb', mode=DbWriteMode.ASYNC) - -* `~.ServerDbServices.set_access_mode()` - Sets database access mode (R/W or R/O). - - .. sourcecode:: python - - >>> from firebird.driver import connect_server, DbAccessMode - >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - >>> srv.database.set_access_mode(database='employee.fdb', mode=DbAccessMode.READ_ONLY) - -* `~.ServerDbServices.set_sql_dialect()` - Sets database SQL dialect. - - .. warning:: - - Changing SQL dialect on existing database is not recommended. Only newly created - database objects would respect new dialect setting, while objects created with - previous dialect remain unchanged. That may have dire consequences. - - .. sourcecode:: python - - >>> from firebird.driver import connect_server - >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - >>> srv.database.set_sql_dialect(database='employee.fdb', dialect=1) - -* `~.ServerDbServices.no_linger()` - Sets one-off override for database linger. - - .. sourcecode:: python - - >>> from firebird.driver import connect_server - >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - >>> srv.database.no_linger(database='employee.fdb') - -.. index:: - triple: Services; Database; maintenance - -Database maintenance --------------------- - -.. important:: - - Because available database-related actions depends on the version of the Firebird - server, they are made available through a separate class `.ServerDbServices`. - The `.Server.database` property provides access to instance of `.ServerDbServices` or - it's **ancestor** class according to attached Firebird server version. - -* `~.ServerDbServices3.get_statistics()` - Returns database statistics produced by gstat - utility. - - This method is so-called `Async service` that only initiates report processing. Actual - report content could be read by one from many methods for `text output from Services`_ that - `.Server` provides . - - .. sourcecode:: python - - from firebird.driver import connect_server, SrvStatFlag - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.get_statistics(database='employee.fdb', - flags=SrvStatFlag.DATA_PAGES | SrvStatFlag.RECORD_VERSIONS), - tables=['EMPLOYEE','PROJECT']) - stats = srv.readlines() - -* `~.ServerDbServices3.backup()` - Performs logical (GBAK) database backup. - - This method is so-called `Async service` that only initiates the backup process. Output - from gbak could be read by one from many methods for `text output from Services`_ that - `.Server` provides . - - .. sourcecode:: python - - from firebird.driver import connect_server, SrvBackupFlag - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.backup(database='employee.fdb', - backup='/backup/employee.fbk', - flags=SrvBackupFlag.IGNORE_CHECKSUMS | SrvBackupFlag.NO_GARBAGE_COLLECT, - stats='TD', verbose=True) - report = srv.readlines() - -* `~.ServerDbServices3.local_backup()` - Performs logical (GBAK) database backup into local byte - stream. - - .. sourcecode:: python - - from firebird.driver import connect_server, SrvBackupFlag - f = open('/backup/employee.fbk',mode='wb') - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.local_backup(database='employee.fdb', backup_stream=f, - flags=SrvBackupFlag.IGNORE_CHECKSUMS | SrvBackupFlag.NO_GARBAGE_COLLECT) - f.close() - -* `~.ServerDbServices3.restore()` - Performs database restore from logical (GBAK) backup. - - This method is so-called `Async service` that only initiates the restore process. Output - from gbak could be read by one from many methods for `text output from Services`_ that - `.Server` provides . - - .. sourcecode:: python - - from firebird.driver import connect_server, SrvRestoreFlag - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.restore(backup='/backup/employee.fbk', - database='/data/employee.fdb', - flags=SrvRestoreFlag.REPLACE, - stats='TD', verbose=True, page_size=8192) - report = srv.readlines() - -* `~.ServerDbServices3.local_restore()` - Performs database restore from logical (GBAK) backup - stored in local byte stream. - - .. sourcecode:: python - - from firebird.driver import connect_server, SrvRestoreFlag - f = open('/backup/employee.fbk',mode='rb') - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.local_restore(backup_stream=f, database='/data/employee.fdb', - flags=SrvRestoreFlag.REPLACE, page_size=8192) - f.close() - -* `~.ServerDbServices3.nbackup()` - Performs physical (NBACKUP) database backup. - - .. sourcecode:: python - - from firebird.driver import connect_server - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.nbackup(database='employee.fdb', backup='/backup/employee.bkp1', level=1) - -* `~.ServerDbServices3.nrestore()` - Performs restore from physical (NBACKUP) database - backup. - - .. sourcecode:: python - - from firebird.driver import connect_server - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.nrestore(backups=['/backup/employee.bkp0', '/backup/employee.bkp1'], - database='/data/employee.fdb') - -* `~.ServerDbServices3.shutdown()` - Database shutdown. - - .. sourcecode:: python - - from firebird.driver import connect_server, ShutdownMode, ShutdownMethod - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.shutdown(database='employee.fdb', mode=ShutdownMode.SINGLE, - method=ShutdownMethod.FORCED, timeout=10) - -* `~.ServerDbServices3.bring_online()` - Bring previously shut down database back online. - - .. sourcecode:: python - - from firebird.driver import connect_server, OnlineMode - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.bring_online(database='employee.fdb', mode=OnlineMode.MULTI) - -* `~.ServerDbServices3.sweep()` - Performs database sweep operation. - - .. sourcecode:: python - - from firebird.driver import connect_server - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.sweep(database='employee.fdb') - -* `~.ServerDbServices3.validate()` - Performs database validation. - - This method is so-called `Async service` that only initiates the validation process. Output - from validation could be read by one from many methods for `text output from Services`_ that - `.Server` provides . - - .. sourcecode:: python - - from firebird.driver import connect_server - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.validate(database='employee.fdb') - report = srv.readlines() - -* `~.ServerDbServices3.repair()` - Performs database repair operation. - - .. sourcecode:: python - - from firebird.driver import connect_server, SrvRepairFlag - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.repair(database='employee.fdb', - flags=SrvRepairFlag.REPAIR | SrvRepairFlag.KILL_SHADOWS) - -* `~.ServerDbServices3.get_limbo_transaction_ids()` - Returns list of transactions in limbo. - -* `~.ServerDbServices3.commit_limbo_transaction()` - Resolves limbo transaction with commit. - -* `~.ServerDbServices3.rollback_limbo_transaction()` - Resolves limbo transaction with rollback. - -* `~.ServerDbServices.nfix_database` - Fixup database after filesystem copy. - -* `~.ServerDbServices.set_replica_mode` - Manage replica database. - -.. index:: - triple: Services; Database; users - -User maintenance ----------------- - -.. important:: - - Because user maintenance functionality may depend on the version of the Firebird - server, this functionality is made available through a separate class - `.ServerUserServices`. The `.Server.user` property provides access to - instance of `.ServerUserServices` or it's **ancestor** class according to attached - Firebird server version. - -.. tip:: - - Since Firebird 2.5 you can use SQL commands (CREATE/ALTER/DROP USER) to manage users in - a security database from a regular database attachment. - - The SQL set of DDL commands for managing user accounts has been further enhanced in Firebird 3, - thus improving the DDL capabilities in a way that exceeds capabilities of user management services. - -* `~.ServerUserServices.get_all()` - Returns information about all users. - -* `~.ServerUserServices.get()` - Returns information about specified users. - -* `~.ServerUserServices.add()` - Add new user. - -* `~.ServerUserServices.update()` - Update user information. - -* `~.ServerUserServices.delete()` - Delete user. - -* `~.ServerUserServices.exists()` - Returns True if user exists. - -.. index:: - pair: Services; trace - -Trace sessions --------------- - -.. important:: - - Because trace functionality may depend on the version of the Firebird server, this - functionality is made available through a separate class `.ServerTraceServices`. - The `.Server.trace` property provides access to instance of `.ServerTraceServices` or - its **ancestor** class according to attached Firebird server version. - - -* `.ServerTraceServices.start()` - Start new trace session. Requires trace `configuration` and returns `Session ID`. - - This method is so-called `Async service` that only starts the trace session. Output - from trace session could be read by one from many methods for `text output from Services`_ - that `.Server` provides . - - .. sourcecode:: python - - from firebird.driver import connect_server - - trace_config = """database = %[\\/]employee.fdb - { - enabled = true - log_statement_finish = true - print_plan = true - include_filter = %%SELECT%% - exclude_filter = %%RDB$%% - time_threshold = 0 - max_sql_length = 2048 - } - """ - - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - trace_id = srv.trace.start(trace_config,'test_trace_1') - trace_log = [] - # Get first 10 lines of trace output - for i in range(10): - trace_log.append(srv.readline()) - # Stop trace session - # Because trace session blocks the connection, we need another one to stop trace session! - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv_aux: - srv_aux.trace.stop(trace_id) - -* `.ServerTraceServices.stop()` - Stop trace session. - -* `.ServerTraceServices.suspend()` - Suspend trace session. - -* `.ServerTraceServices.resume()` - Resume trace session. - -* `.ServerTraceServices.sessions` - Dictionary with active trace sessions. The key is session ID, value is `.TraceSession` instance. - - -.. index:: Logging - pair: driver; logging - -Logging driver activities -========================= - -The firebird-driver supports `context-based logging system ` -provided by `firebird-base`_ package through use of `~firebird.base.logging.LoggingIdMixin`. - -Classes that use `~firebird.base.logging.LoggingIdMixin`: - -* `.Connection` - Internally used objects have `_logging_id_` set to 'Transaction.Main', - 'Transaction.Query' and 'Cursor.internal'. The log context is not defined. -* `.TransactionManager` - The `_logging_id_` is set to 'Transaction'. The - `~.TransactionManager.log_context()` is the `.Connection`. -* `.DistributedTransactionManager` - The `_logging_id_` is set to 'DTransaction'. The - `~.DistributedTransactionManager.log_context()` is `~firebird.base.types.UNDEFINED`. -* `.Statement` - The `~.Statement.log_context()` is `.Connection`. -* `.BlobReader` - The `~.Statement.log_context()` is the owning object or `~firebird.base.types.UNDEFINED`. -* `.Cursor` - The `~.Cursor.log_context()` is `.Connection`. -* `.Server` - The log context is not defined. - -**Example:** - -.. sourcecode:: python - - import logging - from firebird.base.logging import get_logger, LogLevel - from firebird.driver import connect, driver_config - - # Helper function - def execute(cur: Cursor, cmd: str) -> None: - get_logger(cur).debug(f"Execute [{cmd=}]") - cur.execute(cmd) - - # Basic Python logging configuration - sh = logging.StreamHandler() - sh.setFormatter(logging.Formatter('%(levelname)-10s: [%(agent)s][%(context)s] %(message)s')) - logger = logging.getLogger() - logger.addHandler(sh) - logger.setLevel(LogLevel.DEBUG) - - # Firebird driver configuration - srv_cfg = """[local] - host = localhost - user = SYSDBA - password = masterkey - """ - driver_config.register_server('local', srv_cfg) - db_cfg = """[employee] - server = local - database = employee.fdb - protocol = inet - """ - driver_config.register_database('employee', db_cfg) - - print("Default logging ids") - with connect('employee') as con: - con_log = get_logger(con) - con_log.info('Start') - cur1 = con.cursor() - cur2 = con.cursor() - execute(cur1, 'select * from country') - execute(cur2, 'select * from project') - con_log.info('Stop') - - print("Custom logging ids") - with connect('employee') as con: - con._logging_id_ = 'employee-1' - con_log = get_logger(con) - con_log.info('Start') - cur1 = con.cursor() - cur1._logging_id_ = 'cursor-1' - cur2 = con.cursor() - cur2._logging_id_ = 'cursor-2' - execute(cur1, 'select * from country') - execute(cur2, 'select * from project') - con_log.info('Stop') - -Output:: - - Default logging ids - INFO : [Connection][UNDEFINED] Start - DEBUG : [Cursor][Connection] Execute [cmd='select * from country'] - DEBUG : [Cursor][Connection] Execute [cmd='select * from project'] - INFO : [Connection][UNDEFINED] Stop - Custom logging ids - INFO : [employee-1][UNDEFINED] Start - DEBUG : [cursor-1][employee-1] Execute [cmd='select * from country'] - DEBUG : [cursor-2][employee-1] Execute [cmd='select * from project'] - INFO : [employee-1][UNDEFINED] Stop - -You can also trace the driver activities using `trace/audit for class instances ` -provided by `firebird-base`_ package. - -**Example:** - -.. sourcecode:: python - - import logging - from firebird.base.logging import get_logger, LogLevel - from firebird.base.trace import trace_manager, add_trace, trace_object, traced, TraceFlag - from firebird.driver import connect, driver_config - from firebird.driver.core import TransactionManager - - # Helper function - def execute(cur: Cursor, cmd: str) -> None: - cur.execute(cmd) - - # Basic Python logging configuration - sh = logging.StreamHandler() - sh.setFormatter(logging.Formatter('%(levelname)-10s: [%(agent)s][%(context)s] %(message)s')) - logger = logging.getLogger() - logger.addHandler(sh) - logger.setLevel(LogLevel.DEBUG) - - # Firebird driver configuration - srv_cfg = """[local] - host = localhost - user = SYSDBA - password = masterkey - """ - driver_config.register_server('local', srv_cfg) - db_cfg = """[employee] - server = local - database = employee.fdb - protocol = inet - """ - driver_config.register_database('employee', db_cfg) - - # Trace configuration - # First: register classes and methods that could be traced - trace_manager.register(Connection) - add_trace(Connection, 'close', traced) - trace_manager.register(TransactionManager) - add_trace(TransactionManager, 'begin', traced) - add_trace(TransactionManager, 'commit', traced) - add_trace(TransactionManager, 'rollback', traced) - trace_manager.register(Cursor) - add_trace(Cursor, 'execute', traced) - add_trace(Cursor, 'close', traced) - # Activate trace/audit - trace_manager.trace |= (TraceFlag.ACTIVE | TraceFlag.BEFORE | TraceFlag.AFTER | TraceFlag.FAIL) - - # Traced code - with connect('employee') as con: - trace_object(con) - trace_object(con.main_transaction) - con._logging_id_ = 'employee-1' - cur1 = con.cursor() - trace_object(cur1) - cur1._logging_id_ = 'cursor-1' - cur2 = con.cursor() - trace_object(cur2) - cur2._logging_id_ = 'cursor-2' - execute(cur1, 'select * from country') - execute(cur2, 'select * from project') - con.commit() - -Sample output:: - - DEBUG : [cursor-1][employee-1] >>> execute(operation='select * from country', parameters=None) - DEBUG : [Transaction.Main][employee-1] >>> begin(tpb=None) - DEBUG : [Transaction.Main][employee-1] <<< begin[0.00672] - DEBUG : [cursor-1][employee-1] >>> close() - DEBUG : [cursor-1][employee-1] <<< close[0.00004] - DEBUG : [cursor-1][employee-1] <<< execute[0.01119] Result: cursor-1 - DEBUG : [cursor-2][employee-1] >>> execute(operation='select * from project', parameters=None) - DEBUG : [cursor-2][employee-1] >>> close() - DEBUG : [cursor-2][employee-1] <<< close[0.00002] - DEBUG : [cursor-2][employee-1] <<< execute[0.00352] Result: cursor-2 - DEBUG : [Transaction.Main][employee-1] >>> commit(retaining=False) - DEBUG : [cursor-1][employee-1] >>> close() - DEBUG : [cursor-1][employee-1] <<< close[0.00017] - DEBUG : [cursor-2][employee-1] >>> close() - DEBUG : [cursor-2][employee-1] <<< close[0.00012] - DEBUG : [Transaction.Main][employee-1] <<< commit[0.00225] - DEBUG : [employee-1][UNDEFINED] >>> close() - DEBUG : [employee-1][UNDEFINED] <<< close[0.00764] - - -If you will remove the `con.commit()` from the example above, the output will change to:: - - DEBUG : [cursor-1][employee-1] >>> execute(operation='select * from country', parameters=None) - DEBUG : [Transaction.Main][employee-1] >>> begin(tpb=None) - DEBUG : [Transaction.Main][employee-1] <<< begin[0.00338] - DEBUG : [cursor-1][employee-1] >>> close() - DEBUG : [cursor-1][employee-1] <<< close[0.00003] - DEBUG : [cursor-1][employee-1] <<< execute[0.00730] Result: cursor-1 - DEBUG : [cursor-2][employee-1] >>> execute(operation='select * from project', parameters=None) - DEBUG : [cursor-2][employee-1] >>> close() - DEBUG : [cursor-2][employee-1] <<< close[0.00003] - DEBUG : [cursor-2][employee-1] <<< execute[0.00345] Result: cursor-2 - DEBUG : [employee-1][UNDEFINED] >>> close() - DEBUG : [Transaction.Main][employee-1] >>> rollback(retaining=False, savepoint=None) - DEBUG : [cursor-1][employee-1] >>> close() - DEBUG : [cursor-1][employee-1] <<< close[0.00016] - DEBUG : [cursor-2][employee-1] >>> close() - DEBUG : [cursor-2][employee-1] <<< close[0.00014] - DEBUG : [Transaction.Main][employee-1] <<< rollback[0.00171] - DEBUG : [employee-1][UNDEFINED] <<< close[0.01001] - - -.. _driver-hooks: - -.. index:: - pair: driver; hooks - pair: hooks; usage - - -Driver hooks -============ - -The firebird-driver uses `hook manager ` from `firebird-base`_ package -to provide internal notification mechanism that allows installation of custom hooks into -certain driver tasks. - -Driver hooks are divided into several types exposed as enums in `firebird.driver.hooks` module. - -APIHook -------- - -`.APIHook.LOADED` - This hook is invoked once when instance of `.FirebirdAPI` is created. -It could be used for additional initialization tasks that require Firebird API, or to manipulate -the FirebirdAPI instance itself before its use. - -Hook routine must have signature: `hook_func(api: FirebirdAPI) -> None`. Any value returned -by hook is ignored. - -ConnectionHook --------------- - -* `.ConnectionHook.ATTACH_REQUEST` - - This hook is invoked after all parameters are preprocessed and before `.Connection` is created. - - Hook routine must have signature: `hook_func(dsn: str, dpb: bytes) -> Optional[Connection]` - where `dpb` is Database Parameter Buffer that would be used to create the attachment to the - database defined by `dsn`. It may return `.Connection` (or subclass) instance or `None`. - - First instance returned by any hook of this type will become the return value of caller function - and other hooks of the same type are not invoked. - -* `.ConnectionHook.ATTACHED` - - This hook is invoked just before `.Connection` (or subclass) instance is returned to the client - application. - - Hook routine must have signature: `hook_func(con: Connection) -> None`. - -* `.ConnectionHook.DETACH_REQUEST` - - This hook is invoked before connection is closed. - - Hook must have signature: `hook_func(con: Connection) -> None`. - - If any hook function returns True, connection is not closed. - -* `.ConnectionHook.CLOSED` - - This hook is invoked after connection is closed. - - Hook routine must have signature: `hook_func(con: Connection) -> None`. - -* `.ConnectionHook.DROPPED` - - This hook is invoked after database is dropped (and connection is closed). - - Hook routine must have signature: `hook_func(con: Connection) -> None`. - -ServerHook ----------- - -* `.ServerHook.ATTACHED` - - This hook is invoked before `.Server` instance is returned. - - Hook routine must have signature: `hook_func(srv: Server) -> None`. - -.. index:: - pair: hooks; invocation - - -.. _DDL: http://en.wikipedia.org/wiki/Data_Definition_Language -.. _DML: http://en.wikipedia.org/wiki/Data_Manipulation_Language -.. _Firebird SAVEPOINTs: http://www.firebirdsql.org/refdocs/langrefupd15-savepoint.html -.. _Firebird Book: https://www.ibphoenix.com/products/books/firebird_book -.. _busy-wait: http://www.catb.org/jargon/html/B/busy-wait.html -.. _Visitor Pattern: http://en.wikipedia.org/wiki/Visitor_pattern -.. _setuptools: https://pypi.org/project/setuptools/ -.. _PYPI: https://pypi.org/ -.. _ctypes: http://docs.python.org/library/ctypes.html -.. _pip: https://pypi.org/project/pip/ -.. _firebird-base: https://firebird-base.rtfd.io diff --git a/docs/zensical.toml b/docs/zensical.toml new file mode 100644 index 0000000..d7d91e7 --- /dev/null +++ b/docs/zensical.toml @@ -0,0 +1,45 @@ +[project] +site_name = "The Python driver for Firebird" +site_author = "Pavel Císař" +copyright = "The Firebird Project" +site_url = "https://firebird-driver.readthedocs.io/" +nav = [ + { "Home" = "index.md" }, + { "Getting Started" = "getting-started.md" }, + { "Usage Guide" = "usage-guide.md" }, + { "Python DB API compliance" = "python-db-api-compliance.md" }, + { "Reference" = [ + { "Main namespace" = "ref-main.md" }, + { "Types" = "ref-types.md" }, + { "Configuration" = "ref-config.md" }, + { "Core" = "ref-core.md" }, + { "Hooks" = "ref-hooks.md" }, + { "Interfaces" = "ref-intf.md" }, + { "Client API" = "ref-fbapi.md" }, + ] }, + { "Changelog" = "changelog.md" }, + { "License" = "license.md" }, +] + +[project.theme] +favicon = "assets/fb-favicon.png" +features = [ + "navigation.instant", + "navigation.tracking", + "navigation.tabs", + "navigation.tabs.sticky", + "navigation.sections", + "navigation.expand", + "navigation.path", + "navigation.top", +] + +[project.plugins.mkdocstrings.handlers.python] +paths = ["../src"] +inventories = ["https://docs.python.org/3/objects.inv"] + +[project.plugins.mkdocstrings.handlers.python.options] +docstring_style = "google" +inherited_members = true +show_root_heading = true +show_source = true diff --git a/pyproject.toml b/pyproject.toml index 59b0d6e..5e4aee5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -68,16 +68,18 @@ python = ["3.11", "3.12", "3.13", "3.14"] detached = false platforms = ["linux"] dependencies = [ - "Sphinx==7.2.6", - "sphinx-bootstrap-theme>=0.8.1", - "sphinx-autodoc-typehints>=1.24.0", - "doc2dash>=3.0.0" + "zensical", + "mkdocstrings-python", + "doc2dash>=3.0.0", ] + [tool.hatch.envs.doc.scripts] -build = "cd docs ; make html" +build = "cd docs && zensical build {args}" +serve = "cd docs && zensical serve {args}" docset = [ - "cd docs ; doc2dash -u https://firebird-driver.readthedocs.io/en/latest/ -f -i ./_static/fb-favicon.png -n firebird-driver ./_build/html/", - "cd docs; VERSION=`hatch version` ; tar --exclude='.DS_Store' -cvzf ../dist/firebird-driver-$VERSION-docset.tgz firebird-driver.docset", + "build", + "cd docs && doc2dash -u https://firebird-driver.readthedocs.io/en/latest/ -f -i docs/assets/fb-favicon.png -n firebird-driver site/", + "cd docs && VERSION=$(python -c 'from firebird.driver import __VERSION__; print(__VERSION__)') && tar --exclude='.DS_Store' -czf ../dist/firebird-driver-$VERSION-docset.tgz firebird-driver.docset", ] [tool.ruff] diff --git a/src/firebird/driver/core.py b/src/firebird/driver/core.py index 457c24b..65b238f 100644 --- a/src/firebird/driver/core.py +++ b/src/firebird/driver/core.py @@ -969,7 +969,7 @@ class EventCollector: `EventCollector` implements context manager protocol to call method `.begin()` and `.close()` automatically. - Example:: + Example: with connection.event_collector(['event_a', 'event_b']) as collector: events = collector.wait() @@ -1042,7 +1042,7 @@ def wait(self, timeout: int | float | None=None) -> dict[str, int]: `None` if the wait timed out, otherwise a dictionary that maps `event_name -> event_occurrence_count`. - Example:: + Example: >>> collector = connection.event_collector(['event_a', 'event_b']) >>> collector.begin() @@ -1931,7 +1931,7 @@ def drop_database(self) -> None: Hooks: Event `.ConnectionHook.DROPPED`: Executed after database is sucessfuly dropped. - Hook must have signature:: + Hook must have signature: hook_func(connection: Connection) -> None @@ -1975,16 +1975,14 @@ def close(self) -> None: Hooks: Event `.ConnectionHook.DETACH_REQUEST`: Executed before connection - is closed. Hook must have signature:: + is closed. Hook must have signature: hook_func(connection: Connection) -> bool - .. note:: - - If any hook function returns True, connection is NOT closed. + Note: If any hook function returns True, connection is NOT closed. Event `.ConnectionHook.CLOSED`: Executed after connection is closed. - Hook must have signature:: + Hook must have signature: hook_func(connection: Connection) -> None @@ -2297,7 +2295,7 @@ def connect(database: str | Path, *, user: str | None=None, password: str | None Hooks: Event `.ConnectionHook.ATTACH_REQUEST`: Executed after all parameters are preprocessed and before `Connection` is created. Hook - must have signature:: + must have signature: hook_func(dsn: str, dpb: bytes) -> Optional[Connection] @@ -2306,7 +2304,7 @@ def connect(database: str | Path, *, user: str | None=None, password: str | None of this function and other hooks are not called. Event `.ConnectionHook.ATTACHED`: Executed before `Connection` instance is - returned. Hook must have signature:: + returned. Hook must have signature: hook_func(connection: Connection) -> None @@ -2389,7 +2387,7 @@ def create_database(database: str | Path, *, user: str | None=None, password: st Hooks: Event `.ConnectionHook.ATTACHED`: Executed before `Connection` instance is - returned. Hook must have signature:: + returned. Hook must have signature: hook_func(connection: Connection) -> None @@ -3263,7 +3261,7 @@ def seek(self, offset: int, whence: int=os.SEEK_SET) -> None: """Set the file's current position, like stdio's `fseek()`. See: - :meth:`io.IOBase.seek()` for details. + `io.IOBase.seek()` for details. Arguments: offset: Offset from specified position. @@ -3279,7 +3277,7 @@ def tell(self) -> int: """Return current position in BLOB. See: - :meth:`io.IOBase.tell()` for details. + `io.IOBase.tell()` for details. """ return self.__pos def is_text(self) -> bool: @@ -3988,8 +3986,7 @@ def callproc(self, proc_name: str, parameters: Sequence | None=None) -> None: parameters: Sequence of parameters. Must contain one entry for each argument that the procedure expects. - .. note:: - + Note: If stored procedure does have output parameters, you must retrieve their values saparatelly by `.Cursor.fetchone()` call. This method is not very convenient, but conforms to Python DB API 2.0. If you don't require conformance to Python @@ -5860,7 +5857,7 @@ def connect_server(server: str, *, user: str | None=None, password: str | None=N Hooks: Event `.ServerHook.ATTACHED`: Executed before `Service` instance is - returned. Hook must have signature:: + returned. Hook must have signature: hook_func(server: Server) -> None diff --git a/src/firebird/driver/fbapi.py b/src/firebird/driver/fbapi.py index 26c8fbd..0297915 100644 --- a/src/firebird/driver/fbapi.py +++ b/src/firebird/driver/fbapi.py @@ -1925,15 +1925,15 @@ def exception_from_status(error, status: ISC_STATUS_ARRAY, preamble: str | None= class FirebirdAPI: """Firebird Client API interface object. Loads Firebird Client Library and - exposes `fb_get_master_interface()`. Uses :ref:`ctypes ` + exposes `fb_get_master_interface()`. Uses [`ctypes`](https://docs.python.org/3/library/ctypes.html) for bindings. Arguments: filename (`~pathlib.Path`): Firebird client library to be loaded. If it's not provided, - the driver uses :func:`~ctypes.util.find_library()` to locate the library. + the driver uses `ctypes.util.find_library()` to locate the library. Attributes: - client_library (`~ctypes.ctypes.CDLL`): Loaded Firebird client library :mod:`ctypes` handler + client_library (`ctypes.CDLL`): Loaded Firebird client library `ctypes` handler client_library_name (`~pathlib.Path`): Path to loaded Firebird client library master (iMaster): Firebird API IMaster interface util (iUtil): Firebird API IUtil interface diff --git a/src/firebird/driver/interfaces.py b/src/firebird/driver/interfaces.py index 1359d05..494f57f 100644 --- a/src/firebird/driver/interfaces.py +++ b/src/firebird/driver/interfaces.py @@ -290,7 +290,7 @@ def find_value(self, name: str, value: str) -> iConfigEntry: return iConfigEntry(result) def find_pos(self, name: str, pos: int) -> iConfigEntry: """Find entry by name and position. -If configuration file contains lines:: +If configuration file contains lines: Db=DBA Db=DBB diff --git a/src/firebird/driver/types.py b/src/firebird/driver/types.py index c95abfa..64deff8 100644 --- a/src/firebird/driver/types.py +++ b/src/firebird/driver/types.py @@ -135,7 +135,7 @@ class FirebirdWarning(UserWarning): Attribute lookup on this class never fails, as all attributes that are not actually set, have `None` value. - Example:: + Example: try: if condition: From 19a3dcd6587467fb8d2a8d0ac48ffc33df2f69c9 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Thu, 8 Oct 2026 16:58:06 +0200 Subject: [PATCH 14/48] Better structure for the Usage guide --- docs/docs/getting-started.md | 2 +- docs/docs/index.md | 2 +- docs/docs/usage-guide.md | 3235 ----------------- docs/docs/usage-guide/configuration.md | 57 + .../data-handling-and-conversions.md | 319 ++ docs/docs/usage-guide/database-events.md | 282 ++ docs/docs/usage-guide/databases.md | 496 +++ docs/docs/usage-guide/driver-hooks.md | 70 + docs/docs/usage-guide/driver-structure.md | 53 + .../usage-guide/executing-sql-statements.md | 478 +++ .../usage-guide/logging-driver-activities.md | 207 ++ .../usage-guide/transanction-management.md | 574 +++ .../docs/usage-guide/working-with-services.md | 668 ++++ docs/zensical.toml | 13 +- 14 files changed, 3218 insertions(+), 3238 deletions(-) delete mode 100644 docs/docs/usage-guide.md create mode 100644 docs/docs/usage-guide/configuration.md create mode 100644 docs/docs/usage-guide/data-handling-and-conversions.md create mode 100644 docs/docs/usage-guide/database-events.md create mode 100644 docs/docs/usage-guide/databases.md create mode 100644 docs/docs/usage-guide/driver-hooks.md create mode 100644 docs/docs/usage-guide/driver-structure.md create mode 100644 docs/docs/usage-guide/executing-sql-statements.md create mode 100644 docs/docs/usage-guide/logging-driver-activities.md create mode 100644 docs/docs/usage-guide/transanction-management.md create mode 100644 docs/docs/usage-guide/working-with-services.md diff --git a/docs/docs/getting-started.md b/docs/docs/getting-started.md index 34e27e6..fba6f7b 100644 --- a/docs/docs/getting-started.md +++ b/docs/docs/getting-started.md @@ -263,7 +263,7 @@ con.commit() Note the use of a *parameterized* SQL statement above. When dealing with repetitive statements, this is much faster and less error-prone than assembling each SQL statement manually. (You can read more about parameterized SQL statements in the section on -[Prepared Statements](usage-guide.md#prepared-statements).) +[Prepared Statements](usage-guide/executing-sql-statements.md#prepared-statements).) After running Example 4, the table printer from Example 3 would print: diff --git a/docs/docs/index.md b/docs/docs/index.md index 5361efa..1158915 100644 --- a/docs/docs/index.md +++ b/docs/docs/index.md @@ -28,7 +28,7 @@ written by Helen Borrie and published by [IBPhoenix](http://www.ibphoenix.com). ## Content - [Getting Started](getting-started.md) -- [Usage Guide](usage-guide.md) +- [Usage Guide](usage-guide/driver-structure.md) - [Python Db Api Compliance](python-db-api-compliance.md) - [Reference](ref-main.md) - [Changelog](changelog.md) diff --git a/docs/docs/usage-guide.md b/docs/docs/usage-guide.md deleted file mode 100644 index 5028910..0000000 --- a/docs/docs/usage-guide.md +++ /dev/null @@ -1,3235 +0,0 @@ - -# Usage Guide - - -## Driver structure - -Source code is currently divided into next submodules: - -* `types` - Data types used by driver. -* `interfaces` - Interface wrappers for Firebird new API -* `core` - Main driver source code. -* `fbapi` - Python `ctypes` interface to Firebird client library. -* `config` - Driver configuration. -* `hooks` - Drivers hooks. - -All important data, functions, classes and constants are available directly in `firebird.driver` -name space. In normal circumstances is not necessary to import sub-modules directly. However, -you may need them to access some not so frequently needed driver functionality like driver -hooks, or to implement your own callback interfaces. - -!!! important - - `firebird-driver` is designed to support all Firebird versions starting from version 3.0. - Because each Firebird major version adds new functionality, and Firebird OO API could - be extended even in maintenance releases, the driver isolates volatile functionality - into special class hierarchies. - - For example information about database (provided via `~.iAttachment_v3.get_info()` API - call) is isolated into separate `.DatabaseInfoProvider` class hierarchy. - The `.Connection.info` attribute then provides access to instance of appropriate class - - `.DatabaseInfoProvider` or its ancestor - for connected database. - The `.DatabaseInfoProvider` class **always** provides functionality of most recent - Firebird version supported by driver. - - This layout has several important consequences: - - 1. The `.DatabaseInfoProvider` class may change in major driver release if new Firebird - functionality is introduced. This normally represent no problems for client application - as backward compatibility is guaranteed. - 2. You should check the class hierarchy for "evolving" classes when you start using the - driver, and whenever you upgrade to new **major** driver version. If there are versioned - ancestor classes (they always have Firebird version number in their name) for canonical - (top level) ones, you should adjust your application to deal with situations when - instance of ancestor class is provided by driver instead top-level one, to prevent - run-time exceptions caused by access to functionality not provided by currently attached - Firebird server. - - !!! note - - The same apply for low-level API (`~firebird.driver.interfaces`) with difference - that they may change in minor driver releases (because API could be extended in - Firebird maintenance releases). - - !!! info - - `.DatabaseInfoProvider`, `.TransactionInfoProvider`, `.ServerInfoProvider`, - `.ServerDbServices`, `.ServerUserServices` and `.ServerTraceServices`. - - -## Configuration - -The driver uses configuration built on top of [configuration system](https://firebird-base.readthedocs.io/en/latest/config/) -provided by [firebird-base](https://firebird-base.rtfd.io) package. In addition to global settings, the configuration -also includes the definition of connection parameters to Firebird servers and databases. - -The default configuration connects to embedded server using direct/local connection method. -To access remote servers and databases (or local ones through remote protocols), it's -necessary to adjust default configuration, or `register` them in configuration manager. - -You can manipulate the configuration objects directly, or load configuration from files or -strings (in `.ini-style` `configparser` format). - -### The 'driver_config' object - -The global `.driver_config` object holds all configurable driver parameters, and access -configuration parameters for registered Firebird servers and databases. - -In initial state, all parameters have default values and there are no registered servers -and databases. You can set individual parameter values directly, or you can set multiple -parameters (including registered servers and databases) at once by loading them from -configuration string, dict or file(s). - -!!! important - - If you want to use specific Firebird client library, you must set the value of - `.DriverConfig.fb_client_library` configuration option **before** your application - calls any from following functions: `.connect()`, `~firebird.driver.core.create_database()`, - `.connect_server()`, `.load_api()` or `.get_api()`. - -!!! info - - `.DriverConfig` for list of available methods and parameters. - -### Server and database configuration - -Firebird provides ever-increasing list of parameter options for database and server connections. -To keep the Python API clean and manageable, the `firebird-driver` uses server and database -configuration objects instead function parameters to specify values for almost all such options. -Connection functions then provide a name parameter that can refer to particular server / database -or configuration, and few keyword parameters to specify / override selected options. - -!!! important - - The configuration objects does not allow specification of next options: - - - set database encryption callback (for technical reasons) - - set db_key scope (for security reasons) - - disable garbage collection (for security reasons) - - disable database triggers (for security reasons) - - allow overwrite of existing database with newly created database (for security reasons) - - These options could be specified only as keyword arguments in appropriate functions. - -!!! info - - `.ServerConfig` and `.DatabaseConfig` for list of available methods and parameters. - - -## Databases - -Access to the database is made available through `.Connection` objects. Firebird-driver -provides two constructors for these: - -* `.connect` - Returns `.Connection` to database that already exists. -* `~firebird.driver.core.create_database` - Returns `.Connection` to newly created database. - - - -### Using connect() - -This constructor has one positional and several keyword parameters. - -The value of `database` positional parameter must be one of: - -* name of registered database configuration -* database name / alias - -!!! important - This value **cannot** be DSN / fully qualified Firebird connection string! - -Keyword parameters are intended to override selected configuration options, or to specify -options that are not configurable. - -!!! note - - If `database` value is not recognized as name of registered database configuration, - the driver uses `~.DriverConfig.db_defaults` and `~.DriverConfig.server_defaults` - configuration objects. - -A simple database connection is typically established with code such as this: - -```python -from firebird.driver import connect - -# Attach to 'employee' database/alias using embedded server connection -con = connect('employee', user='sysdba', password='masterkey') - -# Attach to 'employee' database/alias using local server connection -from firebird.driver import driver_config -driver_config.server_defaults.host.value = 'localhost' -con = connect('employee', user='sysdba', password='masterkey') - -# Set 'user' and 'password' via configuration -driver_config.server_defaults.user.value = 'SYSDBA' -driver_config.server_defaults.password.value = 'masterkey' -con = connect('employee') - -``` - -However, it's recommended to use specific configuration for servers and databases. -It's possible to register servers and databases directly in code like this: - -```python -from firebird.driver import connect, driver_config - -# Register Firebird server -srv_cfg = """[local] -host = localhost -user = SYSDBA -password = masterkey -""" -driver_config.register_server('local', srv_cfg) - -# Register database -db_cfg = """[employee] -server = local -database = employee.fdb -protocol = inet -charset = utf8 -""" -driver_config.register_database('employee', db_cfg) - -# Attach to 'employee' database -con = connect('employee') - -``` - -But more convenient approach is using single configuration file: - -```text -# file: myapp.cfg - -[firebird.driver] -servers = local -databases = employee - -[local] -host = localhost -user = SYSDBA -password = masterkey - -[employee] -server = local -database = employee.fdb -protocol = inet -charset = utf8 - -``` - -```python -from firebird.driver import connect, driver_config - -driver_config.read('myapp.cfg') - -# Attach to 'employee' database -con = connect('employee') - -``` - -!!! info - `.connect()` for details. - - -### Using create_database() - -This constructor returns connection to newly created database. It works in the same way -as `.connect()`, but utilizes additional database configuration options. - -It's possible to specify these options in code like this: - -```python -from firebird.driver import connect, driver_config - -# Register Firebird server -srv_cfg = """[local] -host = localhost -user = SYSDBA -password = masterkey -""" -driver_config.register_server('local', srv_cfg) - -# Register database -db_cfg = """[mydb] -server = local -database = mydb.fdb -protocol = inet -charset = utf8 -# create options -page_size = 16384 -db_charset = utf8 -sweep_interval = 80000 -reserve_space = no -""" -driver_config.register_database('mydb', db_cfg) - -# create 'mydb' database -con = create_database('mydb') - -``` - -But more convenient approach is using single configuration file: - -```text -# file: myapp.cfg - -[firebird.driver] -servers = local -databases = mydb - -[local] -host = localhost -user = SYSDBA -password = masterkey - -[mydb] -server = local -database = mydb.fdb -protocol = inet -charset = utf8 -# create options -page_size = 16384 -db_charset = utf8 -sweep_interval = 80000 -reserve_space = no - -``` - -```python -from firebird.driver import create_database, driver_config - -driver_config.read('myapp.cfg') - -# create 'mydb' database -con = create_database('mydb') - -``` - -!!! info - `~firebird.driver.core.create_database()` for details. - - -### Deleting databases - -The Firebird engine also supports dropping (deleting) databases dynamically, -but dropping is a more complicated operation than creating, for several reasons: -an existing database may be in use by users other than the one who requests -the deletion, it may have supporting objects such as temporary sort files, and -it may even have dependent shadow databases. Although the database engine -recognizes a `DROP DATABASE` SQL statement, support for that statement is limited -to the `isql` command-line administration utility. However, the engine supports -the deletion of databases via an API call, which `firebird-driver` exposes as -`~.Connection.drop_database` method in `.Connection` class. So, to drop a database -you need to connect to it first. - -**Example:** - -```python -from firebird.driver import connect, driver_config - -driver_config.read('myapp.cfg') - -# Attach to 'myapp' database -con = connect('myapp') -con.drop_database() - -``` - -!!! info - `.Connection.drop_database()` for details. - - -### Connection object - -`.Connection` object represents a direct link to database, and works as -gateway for next operations with it: - -* [Executing SQL Statements](usage-guide.md#executing-sql-statements): methods `~.Connection.execute_immediate()` and `~.Connection.cursor()`. -* [Dropping database](usage-guide.md#deleting-databases): method `~.Connection.drop_database()`. -* [Transanction management](usage-guide.md#transanction-management): methods `~.Connection.begin()`, `~.Connection.commit()`, - `~.Connection.rollback()`, `~.Connection.savepoint()`, `~.Connection.transaction_manager()`, - `~.Connection.is_active()`, and attributes `~.Connection.main_transaction`, - `~.Connection.query_transaction`, `~.Connection.transactions` and `~.Connection.default_tpb`. -* Work with [Database Events](usage-guide.md#database-events): method `~.Connection.event_collector`. -* [Getting information about connection](usage-guide.md#getting-information-about-connection): methods `~.Connection.is_closed()` and - `~.Connection.ping()` and attributes `~.Connection.dsn`, `~.Connection.charset` - and `~.Connection.sql_dialect`. -* [Getting information about database](usage-guide.md#getting-information-about-database): attribute `~.Connection.info`. -* [Closing the connection](usage-guide.md#closing-the-connection): method `~.Connection.close()` - - -### Closing the connection - -There are many local and server resources used by firebird-driver that must be properly -managed, and disposed when they are no longer necessary. All objects that require proper -finalization provide `close()` method that must be called when object is no longer needed. -The `.Connection` (and `.Server`) objects are the most important ones, as other most frequently -used objects like cursors, prepared statements and transactions are typically associated with -connections. - -You may call the `close()` method directly, or use the with statement -and context manager support provided by all these objects. - -**Example:** - -```python -from firebird.driver import connect, driver_config - -driver_config.read('myapp.cfg') - -with connect('employee') as con: - cur = con.cursor() - cur.execute('select 1 from rdb$database') - print(cur.fetchone()[0]) - - -``` - -!!! note - - Objects that require proper finalization are: `.Connection`, `.TransactionManager` - and `.DistributedTransactionManager`, `.Statement`, `.BlobReader`, `.Cursor` and `.Server`. - - Although only `.Connection` and `.Server` objects must be closed directly because - all other objects are associated with them and thus closed when connection is - closed, it's **recommended** to directly close any resource object obtained by - your code when it's no longer needed (either directly by calling `close()` or using - `with` statement). - -!!! important - - All managed objects have `~object.__del__` method, which ensures that the object in - the active state is properly closed before it is destroyed by the Python memory manager. - However, **the close operation may fail** as the state of your application could be arbitrary - and the sequence in which objects are disposed by memory manager is not deterministic. - - The `~object.__del__` methods should be thus considered as safe guard of last resort - that your code should not rely upon. To indicate that your code is not managing - resources properly, the `ResourceWarning` is raises when active object is disposed - by memory manager. - - !!! note - - Such warnings may not reach your attention if warnings are disabled or filtered - on your system. You should always develop and test your applications with enabled - delivery of resource warnings. - -!!! info - `.Connection.close()` for details. - - -### Getting information about connection - -Only (most useful) part of information associated with `.Connection` object is directly -available: - -* It's possible to check whether Connection object is closed or not with - `~.Connection.is_closed()` method. -* It's possible to check whether connection to the Firebird server is not broken with - `~.Connection.ping()` method. -* The DSN (fully qualified Firebird database connection string) is surfaced as `~.Connection.dsn` - read-only property. -* The character set used by Connection is surfaced as `~.Connection.charset` read-only property. -* The SQL dialect used by Connection is surfaced as `~.Connection.sql_dialect` read-only property. - -!!! tip - - Additional connection-specific information is currently held as `bytes` in protected - `Connection._dpb` attribute that could be processed using `~firebird.driver.core.DPB` object. - - -### Getting information about database - -!!! important - - Because the scope and type of database information depends on the version of the Firebird - server and database ODS, this information is made available through a separate class - `.DatabaseInfoProvider`. The `.Connection.info` property provides access to - instance of `.DatabaseInfoProvider` or it's **ancestor** class according to ODS of attached - database and Firebird version. - -Although you may query the information directly from server using -`~firebird.driver.core.DatabaseInfoProvider3.get_info()` method (that wraps the Firebird -`.iAttachment.getInfo()` API call), the `.DatabaseInfoProvider` object -provides more convenient methods and properties for obtaining specific information directly. - -!!! note - - Some information provided by `.DatabaseInfoProvider` properties - (like `~.DatabaseInfoProvider3.cache_hit_ratio`) could not be obtained via - `get_info()` method. - -**Example:** - -```python -from firebird.driver import connect - -with connect('employee', user='SYSDBA', password='masterkey') as con: - print(f"Database character set: {con.info.charset}") - print(f"Page size (in bytes): {con.info.page_size}") - print(f"Attachment ID: {con.info.id}") - print(f"SQL dialect used by connected database: {con.info.sql_dialect}") - print(f"Database name (filename or alias): {con.info.name}") - print(f"Database site name: {con.info.site}") - print(f"Implementation (old format): {con.info.implementation!s}") - print(f"Database Provider: {con.info.provider!s}") - print(f"Database Class: {con.info.db_class!s}") - print(f"Date when database was created: {con.info.creation_date}") - print(f"Size of page cache used by connection: {con.info.page_cache_size}") - print(f"Number of pages allocated for database: {con.info.pages_allocated}") - print(f"Number of database pages in active use: {con.info.pages_used}") - print(f"Number of free allocated pages in database: {con.info.pages_free}") - print(f"Sweep interval: {con.info.sweep_interval}") - print(f"Data page space usage (USE_FULL or RESERVE): {con.info.space_reservation!s}") - print(f"Database write mode (SYNC or ASYNC): {con.info.write_mode!s}") - print(f"Database access mode (READ_ONLY or READ_WRITE): {con.info.access_mode!s}") - print(f"Current I/O statistics - Reads from disk to page cache: {con.info.reads}") - print(f"Current I/O statistics - Fetches from page cache: {con.info.fetches}") - print(f"Cache hit ratio = 1 - (reads / fetches): {con.info.cache_hit_ratio}") - print(f"Current I/O statistics - Writes from page cache to disk: {con.info.writes}") - print(f"Current I/O statistics - Writes to page in cache: {con.info.marks}") - print(f"Total amount of memory curretly used by database engine: {con.info.current_memory}") - print(f"Max. total amount of memory so far used by database engine: {con.info.max_memory}") - print(f"ID of Oldest Interesting Transaction: {con.info.oit}") - print(f"ID of Oldest Active Transaction: {con.info.oat}") - print(f"ID of Oldest Snapshot Transaction: {con.info.ost}") - print(f"ID for next transaction: {con.info.next_transaction}") - -``` - -**Sample output**: - -```text -Database character set: NONE -Page size (in bytes): 8192 -Attachment ID: 378 -SQL dialect used by connected database: 3 -Database name (filename or alias): /opt/firebird/examples/empbuild/employee.fdb -Database site name: NewAmarisk -Implementation (old format): Implementation.RDB_VMS -Database Provider: DbProvider.FIREBIRD -Database Class: DbClass.SERVER_ACCESS -Date when database was created: 2020-05-13 10:13:57.005010 -Size of page cache used by connection: 2048 -Number of pages allocated for database: 346 -Number of database pages in active use: 311 -Number of free allocated pages in database: 35 -Sweep interval: 20000 -Data page space usage (USE_FULL or RESERVE): DbSpaceReservation.RESERVE -Database write mode (SYNC or ASYNC): DbWriteMode.SYNC -Database access mode (READ_ONLY or READ_WRITE): DbAccessMode.READ_WRITE -Current I/O statistics - Reads from disk to page cache: 87 -Current I/O statistics - Fetches from page cache: 1525 -Cache hit ratio = 1 - (reads / fetches): 0.9429508196721311 -Current I/O statistics - Writes from page cache to disk: 2 -Current I/O statistics - Writes to page in cache: 5 -Total amount of memory curretly used by database engine: 21925248 -Max. total amount of memory so far used by database engine: 22033760 -ID of Oldest Interesting Transaction: 307 -ID of Oldest Active Transaction: 308 -ID of Oldest Snapshot Transaction: 308 -ID for next transaction: 308 - -``` - -!!! info - `.DatabaseInfoProvider` for details. - -#### Getting information about Firebird version - -Because functionality and some features depends on actual Firebird version, it could be -important for driver users to check it. This (otherwise) simple task could be confusing -for new Firebird users, because Firebird uses two different version lineages. This abomination -was introduced to Firebird thanks to its InterBase legacy (Firebird 1.0 is a fork of InterBase -6.0), as applications designed to work with InterBase can often work with Firebird without -problems (and vice versa). - -`.DatabaseInfoProvider` provides these version strings as two properties: - -* `~.DatabaseInfoProvider.server_version` - Legacy InterBase-friendly version string. -* `~.DatabaseInfoProvider.firebird_version` - Firebird’s own version string. - -However, this version string contains more information than version number. For example for -Linux Firebird 4.0.0 it’s ‘LI-T4.0.0.1963 Firebird 4.0 Beta 2’. So `.DatabaseInfoProvider` -provides two more properties for your convenience: - -* `~.DatabaseInfoProvider.version` - Only Firebird version number. It’s a string with - format: major.minor.subrelease.build -* `~.DatabaseInfoProvider.engine_version` - Engine (major.minor) version as (float) number. - - -**Example:** - -```python -from firebird.driver import connect - -with connect('employee', user='SYSDBA', password='masterkey') as con: - print(f"server_version: '{con.info.server_version}'") - print(f"firebird_version: '{con.info.firebird_version}'") - print(f"version: '{con.info.version}'") - print(f"engine_version: {con.info.engine_version}") - -``` - -**Sample output**: - -```text -server_version: 'LI-T6.3.0.1963 Firebird 4.0 Beta 2' -firebird_version: 'LI-T4.0.0.1963 Firebird 4.0 Beta 2' -version: '4.0.0.1963' -engine_version: 4.0 - -``` -#### Database On-Disk Structure - -Particular Firebird features may also depend on specific support in database -(for example number and structure of monitoring tables). These required structures are -present automatically when database is created by particular engine verison that needs -them, but Firebird engine may work with databases created by older versions and thus with -older structure, so it could be necessary to consult also On-Disk Structure (ODS for short) -version. `.DatabaseInfoProvider` provides this number as `~.DatabaseInfoProvider.ods` (float) -property. - -**Example:** - -```python -from firebird.driver import connect - -with connect('employee', user='SYSDBA', password='masterkey') as con: - print(f"ods: {con.info.ods}") - print(f"ods_version: {con.info.ods_version}") - print(f"ods_minor_version: {con.info.ods_minor_version}") - -``` - -**Sample output**: - -```text -ods: 13.0 -ods_version: 13 -ods_minor_version: 0 - - - -``` - -## Executing SQL Statements - -Firebird-driver implements two ways for execution of SQL commands against connected database: - -* `~.Connection.execute_immediate` - for execution of SQL commands that don't return any result. -* `.Cursor` objects that offer rich interface for execution of SQL commands and fetching their results. - - - -### Cursor object - -Because `.Cursor` objects always operate in context of single `.Connection` (and `.TransactionManager`), -`.Cursor` instances are not created directly, but by constructor method. Python DB API 2.0 assumes -that if database engine supports transactions, it supports only one transaction per connection, -hence it defines constructor method `~.Connection.cursor` (and other transaction-related methods) -as part of `.Connection` interface. However, Firebird supports multiple independent transactions -per connection. To conform to Python DB API, firebird-driver uses concept of internal -`~.Connection.main_transaction` and secondary `~.Connection.transactions`. Cursor constructor is -primarily defined by `.TransactionManager`, and Cursor constructor on `.Connection` is therefore -a shortcut for `main_transaction.cursor()`. - -`.Cursor` objects are used for next operations: - -* Execution of SQL Statemets: methods `~.Cursor.execute()`, `~.Cursor.executemany()`, `~.Cursor.open()` - and `~.Cursor.callproc()`. -* Creating `.Statement` objects for efficient repeated execution of SQL statements, and to obtain - additional information about SQL statements (like execution `~.Statement.plan`): method `~.Cursor.prepare()`. -* [Fetching results](usage-guide.md#fetching-data-from-server): methods `~.Cursor.fetchone()`, `~.Cursor.fetchmany()`, - `~.Cursor.fetchall()`, `~.Cursor.fetch_next()`, `~.Cursor.fetch_prior()`, `~.Cursor.fetch_first()`, - `~.Cursor.fetch_last()`, `~.Cursor.fetch_absolute()` and `~.Cursor.fetch_relative()`. - - -### SQL Execution Basics - -There are five methods how to execute SQL commands: - -1. `.Connection.execute_immediate()` or `.TransactionManager.execute_immediate()` for SQL commands - that don't return any result, and are not executed frequently. This method also **doesn't** - support either [parameterized statements](usage-guide.md#parameterized-statements) or - [prepared statements](usage-guide.md#prepared-statements). - - !!! tip - - This method is efficient for `administrative` and [DDL](http://en.wikipedia.org/wiki/Data_Definition_Language) SQL commands, like `DROP`, `CREATE` - or `ALTER` commands, `SET STATISTICS` etc. - -2. `.Cursor.execute()` for SQL commands that return result sets, i.e. sequence of `rows` of the same - structure, and sequence has unknown number of `rows` (including zero). Each row of the sequence - can be read only once, and is returned in the order it is read from the server. - - !!! tip - - This method is preferred for all `SELECT` and other [DML](http://en.wikipedia.org/wiki/Data_Manipulation_Language) statements, or any statement that - is executed frequently, either `as is` or in `parameterized` form. - -3. `.Cursor.executemany()` for execution of single parameterized SQL command with various set - of parameters. - - !!! important - - Because `executemany()` is basically a simple loop that calls `execute()` with different - parameters, it's possible to execute any statement acceptable by `execute()`. However, - it's possible to access the result set **only** from last executed command, so this method - should not be used for SQL commands that return results. - -4. `.Cursor.open()` for SQL command that return result sets, i.e. sequence of `rows` of the same - structure, and sequence has unknown number of `rows` (including zero). Instead of just fetching - rows sequentially in a forward direction like `execute()`, this method allows flexible navigation - through an open cursor set both backwards and forwards. Rows next to, prior to and relative to - the current cursor row can be targeted. - - !!! info - [Scrollable cursors](usage-guide.md#scrollable-cursors) for details. - -5. `.Cursor.callproc()` for execution of `Stored procedures` that always return exactly one set - of values. - - !!! note - - This method of SP invocation is equivalent to `"EXECUTE PROCEDURE ..."` SQL statement. - - -### Fetching data from server - -Result of SQL statement execution consists from sequence of zero to unknown number of `rows`, -where each `row` is a set of exactly the same number of values. `.Cursor` object offer number -of different methods for fetching these `rows`, that should satisfy all your specific needs: - -* `~.Cursor.fetchone()` - Returns the next row of a query result set, or `None` when no more data - is available. - - !!! tip - - Cursor supports the [iterator protocol](https://docs.python.org/3/library/stdtypes.html#iterator-types), yielding tuples of values - like `~.Cursor.fetchone()`. - -* `~.Cursor.fetchmany()` - Returns the next set of rows of a query result, returning a sequence - of sequences (e.g. a list of tuples). An empty sequence is returned when no more rows are available. - - The number of rows to fetch per call is specified by the parameter. If it is not given, the - cursor’s `~.Cursor.arraysize` determines the number of rows to be fetched. The method does try - to fetch as many rows as indicated by the size parameter. If this is not possible due to - the specified number of rows not being available, fewer rows may be returned. - - !!! note - - The default value of `~.Cursor.arraysize` is `1`, so without paremeter it's equivalent to - `~.Cursor.fetchone()`, but returns list of `rows`, instead actual `row` directly. - -* `~.Cursor.fetchall()` - Returns all (remaining) rows of a query result as list of tuples, - where each tuple is one row of returned values. - - !!! tip - - This method can potentially return huge amount of data, that may exhaust available memory. - If you need just `iteration` over potentially big result set, use loops with `~.Cursor.fetchone()` - or Cursor's built-in support for [iterator protocol](https://docs.python.org/3/library/stdtypes.html#iterator-types) instead this method. - -* Call to `~.Cursor.execute()` returns `self` (Cursor instance) that itself supports the - [iterator protocol](https://docs.python.org/3/library/stdtypes.html#iterator-types), yielding tuples of values like `~.Cursor.fetchone()`. - -!!! important - - Firebird-driver makes absolutely no guarantees about the `row` return value of the - `fetch*()` methods except that it is a sequence indexed by field position. Therefore, client - programmers should not rely on the return value being an instance of a particular class or type. - -**Examples:** - -```python -from firebird.driver import connect - -with connect('employee', user='SYSDBA', password='masterkey') as con: - cur = con.cursor() - SELECT = "select country, currency from country" - - # 1. Using built-in support for iteration protocol to iterate over the rows available - # from the cursor, unpacking the resulting sequences to yield their elements (country, currency): - cur.execute(SELECT) - for (country, currency) in cur: - print(f"{country} uses {currency} as currency.") - # or alternatively you can take an advantage of cur.execute() returning self. - for (country, currency) in cur.execute(SELECT): - print(f"{country} uses {currency} as currency.") - - # 2. Equivalently using fetchall(): - # This is potentially dangerous if result set is huge, as the whole result set is - # first materialized as list and then used for iteration. - cur.execute(SELECT) - for row in cur.fetchall(): - print(f"{row[0]} uses {row[1]} as currency.") - -``` - -!!! important - - Method `.Cursor.executemany()` is not intended for operations that return results, - so it does **NOT** returns `self` like `.Cursor.execute()`, and you can't use calls - to this method as iterator. - - - - -### Scrollable cursors - -SQL statements executed by `.Cursor.open()` have scrollable result set that could be -navigated using next methods: - -* `~.Cursor.fetch_next()` - Moves the cursor's current position to the next row and - returns it. Returns `None` if the cursor is empty or already positioned at the last row. - -* `~.Cursor.fetch_prior()` - Moves the cursor's current position to the prior row and - returns it. Returns `None` if the cursor is empty or already positioned at the first row. - -* `~.Cursor.fetch_first()` - Moves the cursor's current position to the first row and - returns it. Returns `None` if the cursor is empty. - -* `~.Cursor.fetch_last()` - Moves the cursor's current position to the last row and - returns it. Returns `None` if the cursor is empty. - -* `~.Cursor.fetch_absolute()` - Moves the cursor's current position to the specified - and returns the located row. Returns `None` if is beyond the - cursor's boundaries. - -* `~.Cursor.fetch_relative()` - Moves the cursor's current position backward or forward - by the specified and returns the located row. Returns `None` if the calculated - position is beyond the cursor's boundaries. - -!!! important - - Please note that scrollable cursors: - - a) are not supported by all versions of Firebird server. - - b) are internally materialized as a temporary record set, thus consuming - memory/disk resources, so this feature should be used only when really necessary. - -**Example:** - -```python -from firebird.driver import connect - -def print_row(row): - if row: - print(f"{row[0]}, {row[1]}, {row[2]}") - else: - print('NO DATA') - -with connect('employee', user='SYSDBA', password='masterkey') as con: - cur = con.cursor() - cur.open('select row_number() over (order by country), country, currency from country order by country') - - # You can iterate over scrollable cursors - for row in cur: - print_row(row) - - print('-' * 10) - # or fetch particular rows directly - print_row(cur.fetch_first()) - print_row(cur.fetch_last()) - print_row(cur.fetch_absolute(10)) - print_row(cur.fetch_next()) - print_row(cur.fetch_prior()) - print_row(cur.fetch_relative(-5)) - print_row(cur.fetch_relative(10)) - - print('-' * 10) - - cur.fetch_last() - print_row(cur.fetch_next()) - -``` - -**Sample output**: - -```text -1, Australia, ADollar -2, Austria, Euro -3, Belgium, Euro -4, Canada, CdnDlr -5, England, Pound -6, Fiji, FDollar -7, France, Euro -8, Germany, Euro -9, Hong Kong, HKDollar -10, Italy, Euro -11, Japan, Yen -12, Netherlands, Euro -13, Romania, RLeu -14, Russia, Ruble -15, Switzerland, SFranc -16, USA, Dollar ----------- -1, Australia, ADollar -16, USA, Dollar -10, Italy, Euro -11, Japan, Yen -10, Italy, Euro -5, England, Pound -15, Switzerland, SFranc ----------- -NO DATA - -``` - - - -### Parameterized statements - -When SQL command you want to execute contains data `values`, you can either: - -* Embed them `directly` or via `string formatting` into command string, e.g.: - - ```python - cur.execute("insert into the_table (a,b,c) values ('aardvark', 1, 0.1)") - # or - cur.execute("select * from the_table where col == 'aardvark'") - # or - cur.execute("insert into the_table (a,b,c) values ('%s', %i, %f)" % ('aardvark',1,0.1)) - # or - cur.execute(f"select * from the_table where col == '{value}'") - - ``` - -* Use parameter marker (`?`) in command string in the slots where values are expected, - then supply those values as Python list or tuple: - - ```python - cur.execute("insert into the_table (a,b,c) values (?,?,?)", ('aardvark', 1, 0.1)) - # or - cur.execute("select * from the_table where col == ?",('aardvark',)) - - ``` - -While both methods have the same results, the second one (called `parametrized`) has several -important advantages: - -* You don't need to handle conversions from Python data types to strings. -* Firebird-driver will handle all data type conversions (if necessary) from Python data types - to Firebird ones, including `None/NULL` conversion and conversion from `str` to `bytes` - in encoding expected by server. -* You may pass BLOB values as open `file-like` objects, and firebird-driver will handle the - transfer of BLOB value. - -Parametrized statemets also have some limitations. Currently: - -* `DATE`, `TIME` and `DATETIME` values must be relevant `datetime` objects. -* `NUMERIC` and `DECIMAL` values must be `decimal` objects. - - - - -### Prepared Statements - -Execution of any SQL statement has three phases: - -* *Preparation*: command is analyzed, validated, execution plan is determined - by optimizer and all necessary data structures (for example for input and output - parameters) are initialized. -* *Execution*: input parameters (if any) are passed to server and previously - prepared statement is actually executed by database engine. -* *Fetching*: result of execution and data (if any) are transferred from server - to client, and allocated resources are then released (by closing the statement). - -The preparation phase consumes some amount of server resources (memory and CPU). -Although preparation and release of resources typically takes only small amount -of CPU time, it builds up as number of executed statements grows. Firebird (like -most database engines) allows to spare this time for subsequent execution if -particular statement should be executed repeatedly - by reusing once prepared -statement for repeated execution. This may save significant amount of server -processing time, and result in better overall performance. - -Firebird-driver builds on this by encapsulating the Firebird SQL statement data -and related code into separate `.Statement` class, and implementing the `.Cursor` -class around it. The Cursor uses either an internally managed `.Statement` instance -to execute SQL commands provided as `string`, or uses `.Statement` instance -provided by your code as SQL command. - -To get the (prepared) `.Statement` instance for later (repeated) execution, use -`~.Cursor.prepare()` method. You can then pass this instance to `~.Cursor.execute()`, -`~.Cursor.executemany()` or `~.Cursor.open()` instead `command string`. - -`.Statement` instances are bound to `.Connection` instance, and can't be used -with any other `.Connection`. Beside repeated execution they are also useful -to get information about statement (like its execution `~.Statement.plan` or -`~.Statement.type`) before its execution. - -!!! note - - The internally managed `.Statement` instance is released when `.Cursor` is closed, - or before any new statement is executed. It means that if your code executes - the same SQL command (passed as string) repeatedly without closing the cursor - between calls, the same `.Statement` instance is (re)used. - -!!! important - - Implementation of Cursor in firebird-driver somewhat violates the Python DB API 2.0, - which requires that cursor will be unusable after call to `~.Cursor.close()`; and - an Error (or subclass) exception should be raised if any operation is attempted with - the cursor. In firebird-driver, the `.Cursor.close()` call only releases resources - associated with executed statement like the result set, and you can't fetch data or - query information about the SQL statement. However, you can use the cursor instance - to execute new SQL commands. - - !!! warning - - If you'll take advantage of this anomaly, your code would be less portable to other - Python DB API 2.0 compliant drivers. - -**Example:** - -```python -insertStatement = cur.prepare("insert into the_table (a,b,c) values (?,?,?)") - -inputRows = [ - ('aardvark', 1, 0.1), - ('zymurgy', 2147483647, 99999.999), - ('foobar', 2000, 9.9) - ] - -for row in inputRows: - cur.execute(insertStatement,row) -# -# or you can use executemany -# -cur.executemany(insertStatement, inputRows) - - -``` - -!!! info - `.Statement` for details. - - -### Named Cursors - -To allow the Python programmer to perform scrolling **UPDATE** or **DELETE** via the -**“SELECT ... FOR UPDATE”** syntax, the firebird-driver provides the read-only property -`.Cursor.name` and method `.Cursor.set_cursor_name()`. - -**Example Program:** - -```python -from firebird.driver import connect - -with connect('employee', user='sysdba', password='masterkey') as con: - curScroll = con.cursor() - curUpdate = con.cursor() - - curScroll.execute("select city from customer for update") - curScroll.set_cursor_name('city_scroller') - update = "update customer set city=? where current of " + curScroll.name - - for (city,) in curScroll: - city = ... # make some changes to city - curUpdate.execute( update, (city,) ) - - con.commit() - -``` - - -### Working with stored procedures - -Firebird stored procedures can have input parameters and/or output parameters. -Some databases support input/output parameters, where the same parameter is used -for both input and output; Firebird does not support this. - -It is important to distinguish between procedures that **return a result set** and -procedures that **populate and return their output parameters** exactly once. Conceptually, -the latter “return their output parameters” like a Python function, whereas the former -“yield result rows” like a Python generator. - -Firebird’s **server-side** procedural SQL syntax makes no such distinction, but client-side -SQL code (and C API code) must. A result set is retrieved from a stored procedure by -**SELECT'ing from the procedure, whereas output parameters are retrieved with an -'EXECUTE PROCEDURE' statement**. - -To **retrieve a result set** from a stored procedure with firebird-driver, use code -such as this: - -```python -cur.execute("select output1, output2 from the_proc(?, ?)", (input1, input2)) - -# Ordinary fetch code here, such as: -for row in cur: - ... # process row - -con.commit() # If the procedure had any side effects, commit them. - -``` - -To **execute** a stored procedure and **access its output parameters**, you can -choose from two options: - -1. Method `.Cursor.callproc()` that **conforms to Python DB API 2.0**. This method - does not returns the output parameters directly, and you must call `.Cursor.fetchone()` - **exactly once** to retrieve them. - -2. Method `.Cursor.call_procedure()` that returns output parameters directly - (or `None` if procedure does not have output parameters). - -**Examples:** - -```python -# Python DB API 2.0 compliant method: -cur.callproc("the_proc", (input1, input2)) -# If there are output parameters, retrieve them as though they were the -# first row of a result set... -outputParams = cur.fetchone() - -# alternative method: -outputParams = cur.call_procedure("the_proc", (input1, input2)) - -con.commit() # If the procedure had any side effects, commit them. - - -``` - - -## Data handling and conversions - - -### Implicit Conversion of Input Parameters from Strings - -The Firebird database engine treats most SQL data types in a weakly typed fashion: -the engine may attempt to convert the raw value to a different type, as appropriate -for the current context. For instance, the SQL expressions `123` (integer) and `‘123’` -(string) are treated equivalently when the value is to be inserted into an `integer` -field; the same applies when `‘123’` and `123` are to be inserted into a `varchar` field. - -This weak typing model is quite unlike Python’s dynamic yet strong typing. Although -weak typing is regarded with suspicion by most experienced Python programmers, the -database engine is in certain situations so aggressive about its typing model that -firebird-driver must compromise in order to remain an elegant means of programming -the database engine. - -An example is the handling of “magic values” for date and time fields. The database -engine interprets certain string values such as `‘yesterday’` and `‘now’` as having -special meaning in a date/time context. If firebird-driver did not accept strings as -the values of parameters destined for storage in date/time fields, the resulting code -would be awkward. Consider the difference between the two Python snippets below, which -insert a row containing an integer and a timestamp into a table defined with the following -DDL statement: - -```sql -create table test_table (i integer, t timestamp) - -``` - -```python -i = 1 -t = 'now' -sqlWithMagicValues = f"insert into test_table (i, t) values (?, '{t}')" -cur.execute(sqlWithMagicValues, (i,)) - -``` - -```python -i = 1 -t = 'now' -cur.execute("insert into test_table (i, t) values (?, ?)", (i, t)) - -``` - -If firebird-driver did not support weak parameter typing, string parameters that -the database engine is to interpret as “magic values” would have to be rolled into -the SQL statement in a separate operation from the binding of the rest of the parameters, -as in the first Python snippet above. Implicit conversion of parameter values from -strings allows the consistency evident in the second snippet, which is both more -readable and more general. - -!!! note - - It should be noted that firebird-driver does not perform the conversion from string - itself. Instead, it passes that responsibility to the database engine by changing - the parameter metadata structure dynamically at the last moment, then restoring - the original state of the metadata structure after the database engine has performed - the conversion. - -A secondary benefit is that when one uses firebird-driver to import large amounts -of data from flat files into the database, the incoming values need not necessarily -be converted to their proper Python types before being passed to the database engine. -Eliminating this intermediate step may accelerate the import process considerably, -although other factors such as the chosen connection protocol and the deactivation -of indexes during the import are more consequential. For bulk import tasks, the -database engine’s external tables also deserve consideration. External tables can -be used to suck semi-structured data from flat files directly into the relational -database without the intervention of an ad hoc conversion program. - - -### Automatic conversion from/to Unicode - -In Firebird, every `CHAR`, `VARCHAR` or textual `BLOB` field can (or, better: must) -have a `character set` assigned. While it's possible to define single character set -for whole database, it's also possible to define different character set for each -textual field. This information is used to correctly store the bytes that make up -the character string, and together with collation information (that defines the sort -ordering and uppercase conversions for a string) is vital for correct data manipulation, -including automatic transliteration between character sets when necessary. - -!!! important - - Because data also flow between server and client application, it's vital that client - will send data encoded only in character set(s) that server expects. While it's - possible to leave this responsibility completely on client application, it's better - when client and server settle on single character set they would use for communication, - especially when database operates with multiple character sets, or uses character set - that is not `native` for client application. - - Character set for communication is specified using `~.DatabaseConfig.charset` - configuration option, or parameter in `.connect()` or `~firebird.driver.core.create_database()` call. - - When `connection charset` is defined, all textual data returned from server are encoded - in this charset, and client application must ensure that all textual data sent to server - are encoded only in this charset as well. - -Firebird-driver helps with client side of this character set bargain by automatically -converting Python `str` values into `bytes` encoded in connection character set, -and vice versa. However, developers are still responsible that `bytes` strings -passed to server are in correct encoding (because firebird-driver makes no assumption -about encoding of `bytes` strings, so it can't recode them to connection charset). - -!!! important - - In case that `connection charset` is NOT defined at all, or `NONE` charset is specified, - firebird-driver uses `locale.getpreferredencoding` to determine encoding for conversions - from/to `unicode`. - -!!! important - - There is one exception to automatic conversion: when character set OCTETS is defined - for data column. Values assigned to OCTETS columns are always passed `as is`, because - they're basically binary streams. This has specific implications. Python 3 native - strings are `unicode`, and you would probably want to use `bytes` type instead. However, - firebird-driver in this case doesn't check the value type at all, so you'll not be - warned if you'll make a mistake and pass `str` to OCTETS column (unless you'll pass - more bytes than column may hold, or you intend to store unicode that way). - -Conversion is fully automatic in both directions for all textual data, i.e. including -for string values returned by Firebird Service and `info` calls etc. When `connection -charset` is not specified, firebird-driver uses `locale.getpreferredencoding` to -determine encoding for conversions from/to `unicode`. - -!!! tip - - Except for legacy databases that doesn't have `character set` defined, **always** - define character set for your databases and specify `connection charset`. It will - make your life much easier. - - - - -### Working with TIME/TIMESTAMP WITH TIMEZONE - -Firebird 4 introduced support for TIME and TIMESTAMP WITH TIMEZONE. The driver supports these -types with timezone-aware `datetime.datetime` and `datetime.time` objects. However, this -support has some specific limitations: - -1. The driver uses `python-dateutil` package to handle timezone information. Due to specific - requirements it's not possible to use standard `zoneinfo` package available in Python since - version 3.9, neither any other `datetime.tzinfo` implementation. -2. All timezone-aware `datetime.datetime` and `datetime.time` objects passed to the driver - must use `datetime.tzinfo` created with `.get_timezone()` utility function. - -**Examples:** - -```python -from firebird.driver import get_timezone - -ts_region = datetime.datetime(2020, 12, 31, 23, 55, 35, 123400, get_timezone('Europe/Prague')) -ts_offset = datetime.datetime(2020, 12, 31, 23, 55, 35, 123400, get_timezone('+02:00')) - -``` - -### Working with BLOBs - -Firebird-driver uses two types of BLOB values: - -* **Materialized** BLOB values are Python `str` or `bytes` values. This is the **default** type. -* **Streamed** BLOB values are `file-like` objects. - -Materialized BLOBs are easy to work with, but are not suitable for: - -* **deferred loading** of BLOBs. They're called `materialized` because they're always - fetched from server as part of row fetch. Fetching BLOB value means separate API calls - (and network roundtrips), which may slow down you application considerably. -* **large values**, as they are always stored in memory in full size. - -These drawbacks are addressed by `stream` BLOBs. Using BLOBs in `stream` mode is easy: - -* For **input** values, simply use [parameterized statement](usage-guide.md#parameterized-statements) - and pass any `file-like` object in place of BLOB parameter. The `file-like` object must - implement only the `~file.read` method, as no other method is used. -* For **output** values, add column name(s) that should be returned as `file-like` - objects to `.Cursor.stream_blobs` list attribute. Firebird-driver then returns - `.BlobReader` instance instead string in place of returned BLOB value for these column(s). - -!!! important - - The firebird-driver provides `.Cursor.stream_blob_threshold` attribute that controls - the maximum size of materialized blobs (as memory exhaustion safeguard). When particular - blob value exceeds this threshold, an instance of `.BlobReader` is returned instead - string/bytes value. - - Zero threshold value effectively forces all blobs to be returned as stream blobs. - Negative value means no size limit for materialized blobs (use at your own risk). - Please note that positive threshold value means that your application has to be - prepared to handle BLOBs in both incarnations. - - The default threshold is 64K and could be changed using `.DriverConfig.stream_blob_threshold` - configuration option. - - Blob size threshold has effect only on materialized blob columns, i.e. columns not - explicitly requested to be returned as streamed ones using `.Cursor.stream_blobs` - attribute, that are **always** returned as stream blobs. - -The `.BlobReader` instance is bound to `.Cursor` instance, and it's automatically closed -with cursor. However, it's good practice to use `with` statement or call `.BlobReader.close()` -once you're finished reading to release system resources associated with BLOB value. - -!!! important - - When working with BLOB values, always have memory efficiency in mind, especially when - you're processing huge quantity of rows with BLOB values at once. Materialized BLOB - values may exhaust your memory quickly, but using stream BLOBs may have inpact on - performance too, as new `.BlobReader` instance is created for each value fetched. - -**Example program:** - -```python -from firebird.driver import connect - -with connect('employee', user='SYSDBA', password='masterkey') as con: - cur = con.cursor() - print("Materialized retrieval (as str):") - cur.execute('select proj_id, proj_desc from project') - proj_id, proj_desc = cur.fetchone() - print(f"{proj_id=}, {proj_desc=}") - - print("\nStreaming retrieval (via BlobReader):") - cur.stream_blobs.append('PROJ_DESC') - cur.execute('select proj_id, proj_desc from project') - proj_id, proj_desc = cur.fetchone() - with proj_desc: - print(f"{proj_id=}, {proj_desc=}") - print(proj_desc.read()) - -``` - -Output: - -```text -Materialized retrieval (as str): -proj_id='VBASE', proj_desc='Design a video data base management system for\ncontrolling on-demand video distribution.\n' - -Streaming retrieval (via BlobReader): -proj_id='VBASE', proj_desc=BlobReader[size=89] -Design a video data base management system for -controlling on-demand video distribution. - -``` - -### Firebird ARRAY type - -Firebird-driver supports Firebird ARRAY data type. ARRAY values are represented as -Python lists. On input, the Python sequence (list or tuple) must be nested appropriately -if the array field is multi-dimensional, and the incoming sequence must not fall short -of its maximum possible length (it will not be “padded” implicitly–see below). On output, -the lists will be nested if the database array has multiple dimensions. - -!!! note - - Database arrays have no place in a purely relational data model, which requires that - data values be atomized (that is, every value stored in the database must be reduced - to elementary, non-decomposable parts). The Firebird implementation of database arrays, - like that of most relational database engines that support this data type, is fraught - with limitations. - - Database arrays are of fixed size, with a predeclared number of dimensions (max. 16) - and number of elements per dimension. Individual array elements cannot be set to - NULL / None, so the mapping between Python lists (which have dynamic length and are - therefore not normally “padded” with dummy values) and non-trivial database arrays is - clumsy. - - Stored procedures cannot have array parameters. - - Finally, many interface libraries, GUIs, and even the isql command line utility do not - support database arrays. - - In general, it is preferable to avoid using database arrays unless you have a compelling - reason. - -**Example:** - -```python ->>> from firebird.driver import connect ->>> con = connect('employee',user='sysdba', password='masterkey') ->>> cur = con.cursor() ->>> cur.execute("select LANGUAGE_REQ from job where job_code='Eng' and job_grade=3 and job_country='Japan'") ->>> cur.fetchone() -(['Japanese\n', 'Mandarin\n', 'English\n', '\n', '\n'],) - -``` - -**Example program:** - -```python -from firebird.driver import connect - -arrayIn = [ - [1, 2, 3, 4], - [5, 6, 7, 8], - [9,10,11,12] - ] - -with connect('/temp/test.db', user='sysdba', password='pass') as con: - con.execute_immediate("recreate table array_table (a int[3,4])") - con.commit() - - cur = con.cursor() - - print(f"{arrayIn=}") - cur.execute("insert into array_table values (?)", (arrayIn,)) - con.commit() - - cur.execute("select a from array_table") - arrayOut = cur.fetchone()[0] - print(f"{arrayOut=}) - -``` - -Output: - -```text -arrayIn=[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] -arrayOut=[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] - -``` - -## Transanction management - -For the sake of simplicity, firebird-driver lets the Python programmer ignore -transaction management to the greatest extent allowed by the Python Database -API Specification 2.0. The specification says, “if the database supports an -auto-commit feature, this must be initially off”. At a minimum, therefore, -it is necessary to call the commit method of the connection in order to persist -any changes made to the database. - -Remember that because of ACID, every data manipulation operation in the Firebird -database engine takes place in the context of a transaction, including operations -that are conceptually “read-only”, such as a typical SELECT. The client programmer -of firebird-driver establishes a transaction implicitly by using any SQL execution -method, such as `.Connection.execute_immediate()`, `.Cursor.execute()`, or -`.Cursor.callproc()`. - -Although firebird-driver allows the programmer to pay little attention to transactions, -it also exposes the full complement of the database engine’s advanced transaction -control features: [transaction parameters](usage-guide.md#transaction-parameters), [retaining transactions](usage-guide.md#retaining-transactions), [savepoints](usage-guide.md#savepoints), -and [distributed transactions](usage-guide.md#distributed-transactions). - -### Basics - -When it comes to transactions, Python Database API 2.0 specify that `.Connection` object -has to respond to the following methods: - -`.Connection.commit()` - - Commits any pending transaction to the database. Note that if the database supports - an auto-commit feature, this must be initially off. An interface method may be provided - to turn it back on. Database modules that do not support transactions should implement - this method with void functionality. - -`.Connection.rollback()` - - (optional) In case a database does provide transactions this method causes the the - database to roll back to the start of any pending transaction. **Closing a connection - without committing the changes first will cause an implicit rollback to be performed.** - -In addition to the implicit transaction initiation required by Python Database API, -firebird-driver allows the programmer to start transactions explicitly via the -`.Connection.begin()` method. Also `.Connection.savepoint()` method was added to provide -support for [Firebird SAVEPOINTs](http://www.firebirdsql.org/refdocs/langrefupd15-savepoint.html). - -But Python Database API 2.0 was created with assumption that connection can support only -one transactions per single connection. However, Firebird can support multiple independent -transactions that can run simultaneously within single connection / attachment to the -database. This feature is very important, as applications may require multiple transaction -opened simultaneously to perform various tasks, which would require to open multiple -connections and thus consume more resources than necessary. - -Firebird-driver surfaces this Firebird feature by separating transaction management out -from `.Connection` into separate `.TransactionManager` objects. To comply with Python DB -API 2.0 requirements, `.Connection` object uses one `.TransactionManager` instance as -`main transaction`, and delegates `~.Connection.begin()`, -`~.Connection.savepoint()`, `~.Connection.commit()`, `~.Connection.rollback()` and -`~.Connection.execute_immediate()` calls to it. - -!!! info - - More about using multiple transactions with the same connection in separate - [section](usage-guide.md#multiple_transactions). - -**Example:** - -```python -from firebird.driver import connect - -with connect('employee', user='SYSDBA', password='masterkey') as con: - cur = con.cursor() - - # Most minimalistic transaction management -> implicit start, only commit() and rollback() - # ======================================================================================== - # - # Transaction is started implicitly - cur.execute('insert into country values ('Oz','Crowns') - con.commit() # commits active transaction - # Again, transaction is started implicitly - cur.execute('insert into country values ('Barsoom','XXX') - con.rollback() # rolls back active transaction - cur.execute('insert into country values ('Pellucidar','Shells') - -# Commit was not performed before connection context was closed -# This will roll back the transaction because Python DB API 2.0 -# requires that closing connection with pending transaction must -# cause an implicit rollback - -``` - -!!! info - `.TransactionManager` for details. - - -### Auto-commit - -Firebird-driver doesn't support `auto-commit` feature directly, but developers -may achieve the similar result using `explicit` transaction start, taking advantage -of `.TransactionManager.default_action` and its default value (`~.DefaultAction.COMMIT`). - -**Example:** - -```python -from firebird.driver import connect - -with connect('employee', user='SYSDBA', password='masterkey') as con: - cur = con.cursor() - - con.begin() - cur.execute('insert into country values ('Oz','Crowns') - con.begin() # commits active transaction and starts new one - cur.execute('insert into country values ('Barsoom','XXX') - con.begin() # commits active transaction and starts new one - cur.execute('insert into country values ('Pellucidar','Shells') - - # However, commit is required before connection is closed, - # because Python DB API 2.0 requires that closing connection - # with pending transaction must cause an implicit rollback - con.commit() - -``` - - -### Transaction parameters - -The database engine offers the client programmer an optional facility called -`transaction parameter buffers` (TPBs) for tweaking the operating characteristics -of the transactions he initiates. These include characteristics such as whether -the transaction has read and write access to tables, or read-only access, and -whether or not other simultaneously active transactions can share table access -with the transaction. - -Transaction manager has `~.TransactionManager.default_tpb` attribute that can be -changed to set the default TPB to be used for all subsequent transactions started -by this manager. Also Connection have a `~.Connection.default_tpb` attribute, -but it's used to set the default TPB for all transactions managers subsequently -created for the connection (see `.Connection.transaction_manager()`). - -Alternatively, if the programmer only wants to set the TPB for a single transaction, -he can start a transaction explicitly via the `.Connection.begin()` or -`.TransactionManager.begin()` method and pass a TPB for that single transaction. - -The TPB is a `bytes` value constructed from various tags and binary values, as -defined by API. While you can construct the TPB manually, the firebird-driver -provides several convenient ways for TPB construction: - -1. The `.tpb()` function for simple TPBs. - -2. The `~firebird.driver.core.TPB` class for complex TPBs (including table reservation etc.). - -**Examples:** - -```python -from firebird.driver import tpb, TPB, Isolation, TraAccessMode, TableShareMode, TableAccessMode - -# Use tpb() if isolation, timeout and access_mode parameters are enough for you -simple_tpb = tpb(Isolation.READ_COMMITTED_READ_CONSISTENCY,100,TraAccessMode.WRITE) - -# Use TPB if you want additional parameters than isolation, timeout and access_mode -my_tpb = TPB(isolation=Isolation.SNAPSHOT, - access_mode=TraAccessMode.WRITE, - lock_timeout=100, - no_auto_undo=True, - auto_commit=True, - ignore_limbo=True) -my_tpb.reserve_table('MY_TABLE', TableShareMode.PROTECTED, TableAccessMode.LOCK_WRITE) -complex_tpb = my_tpb.get_buffer() - -``` - - -### Getting information about transaction - -!!! important - - Because the scope and type of transaction information depends on the version of the Firebird - server, this information is made available through a separate class - `.TransactionInfoProvider`. The `.TransactionManager.info` property provides access to - instance of `.TransactionInfoProvider` or it's **ancestor** class according to used - Firebird version. - -Although you may query the information directly from server using -`~.TransactionInfoProvider3.get_info()` method (that wraps the Firebird `ITransaction.getInfo()` -API call), the `.TransactionInfoProvider` object provides more convenient methods and properties -for obtaining specific information directly. - -**Example:** - -```python -from firebird.driver import connect, driver_config - -driver_config.server_defaults.host.value = 'localhost' -with connect('employee', user='SYSDBA', password='masterkey') as con: - con.begin() - info = con.main_transaction.info - print(f"Transaction ID: {info.id}") - print(f"Database: {info.database}") - print(f"Isolation level: {info.isolation!s}") - print(f"Lock timeout: {info.lock_timeout}") - print(f"Is Read-Only: {info.is_read_only()}") - print(f"ID of Oldest Interesting Transaction: {info.oit}") - print(f"ID of Oldest Active Transaction: {info.oat}") - print(f"ID of Oldest Snapshot Transaction: {info.ost}") - -``` - -Output: - -```text -Transaction ID: 352 -Database: localhost:employee -Isolation level: Isolation.SNAPSHOT -Lock timeout: -1 -Is Read-Only: False -ID of Oldest Interesting Transaction: 350 -ID of Oldest Active Transaction: 352 -ID of Oldest Snapshot Transaction: 352 - -``` - -### Retaining transactions - -The `~.TransactionManager.commit()` and `~.TransactionManager.rollback()` methods -accept an optional boolean keyword parameter `retaining` (**default False**) to -indicate whether to recycle the transactional context of the transaction being resolved -by the method call. - -If retaining is `True`, the infrastructural support for the transaction active at -the time of the method call will be “retained” (efficiently and transparently recycled) -after the database server has committed or rolled back the conceptual transaction. - -!!! important - - In code that commits or rolls back frequently in short amount of time (like in loop), - “retaining” the transaction may yield better performance. However, retaining transactions - must be used cautiously because they can interfere with the server’s ability to garbage - collect old record versions. For details about this issue, read the “Garbage” section of - [this document](http://www.ibphoenix.com/resources/documents/search/doc_21) by Ann Harrison. - - It's definitely no recommended to use retaining for all transactions, or retain the transaction - context indefinitely (you should eventually commit/rollback the transaction in normal - way). - -For more information about retaining transactions, see `Firebird documentation`. - - -### Savepoints - -Savepoints are named, intermediate control points within an open transaction that -can later be rolled back to, without affecting the preceding work. Multiple savepoints -can exist within a single unresolved transaction, providing “multi-level undo” functionality. - -Although Firebird savepoints are fully supported from SQL alone via the `SAVEPOINT ‘name’` -and `ROLLBACK TO ‘name’` statements, firebird-driver also exposes savepoints at the Python -API level for the sake of convenience. - -Call to method `.TransactionManager.savepoint()` establishes a savepoint with the specified -`name`. To roll back to a specific savepoint, call the `~.TransactionManager.rollback()` -method and provide the name of the savepoint for the `savepoint` keyword parameter. If the -savepoint parameter of `~.TransactionManager.rollback()` is not specified, the active -transaction is cancelled in its entirety, as required by the Python Database API Specification. - -The following program demonstrates savepoint manipulation via the firebird-driver API, -rather than raw SQL. - -```python -from firebird.driver import connect - -with connect('employee', user='SYSDBA', password='masterkey') as con: - cur = con.cursor() - - cur.execute("recreate table test_savepoints (a integer)") - con.commit() - - print('Before the first savepoint, the contents of the table are:') - cur.execute("select * from test_savepoints") - print(' ', cur.fetchall()) - - cur.execute("insert into test_savepoints values (?)", [1]) - con.savepoint('A') - print('After savepoint A, the contents of the table are:') - cur.execute("select * from test_savepoints") - print(' ', cur.fetchall()) - - cur.execute("insert into test_savepoints values (?)", [2]) - con.savepoint('B') - print('After savepoint B, the contents of the table are:') - cur.execute("select * from test_savepoints") - print(' ', cur.fetchall()) - - cur.execute("insert into test_savepoints values (?)", [3]) - con.savepoint('C') - print('After savepoint C, the contents of the table are:') - cur.execute("select * from test_savepoints") - print(' ', cur.fetchall()) - - con.rollback(savepoint='B') - print('After rolling back to savepoint B, the contents of the table are:') - cur.execute("select * from test_savepoints") - print(' ', cur.fetchall()) - - con.rollback() - print('After rolling back entirely, the contents of the table are:') - cur.execute("select * from test_savepoints") - print(' ', cur.fetchall()) - -``` - -The output of the example program is shown below: - -```text -Before the first savepoint, the contents of the table are: - [] -After savepoint A, the contents of the table are: - [(1,)] -After savepoint B, the contents of the table are: - [(1,), (2,)] -After savepoint C, the contents of the table are: - [(1,), (2,), (3,)] -After rolling back to savepoint B, the contents of the table are: - [(1,), (2,)] -After rolling back entirely, the contents of the table are: - [] - -``` - - - -### Using multiple transactions with the same connection - -To use additional transactions that could run simultaneously with -`main transaction` managed by `.Connection`, -create new `.TransactionManager` object calling `.Connection.transaction_manager()` -method. If you don't specify the optional `default_tpb` parameter, this new -`.TransactionManager` inherits the `~.Connection.default_tpb` from `.Connection`. -Physical transaction is not started when `.TransactionManager` instance is -created, but implicitly when first SQL statement for cursor created from -this manager is executed, or explicitly via `.TransactionManager.begin()` call. - -To execute statements in context of this additional transaction you have to -use `cursors` obtained directly from this `.TransactionManager` instance calling -its `~.TransactionManager.cursor()` method, or call `.TransactionManager.execute_immediate()` -method. - -**Example:** - -```python -from firebird.driver import connect, tpb, Isolation, TraAccessMode - -with connect('employee', user='SYSDBA', password='masterkey') as con: - # Cursor for main_transaction context - cur = con.cursor() - - # Create new READ ONLY READ COMMITTED transaction - ro_transaction = con.transaction_manager(tpb(Isolation.READ_COMMITTED_RECORD_VERSION, - access=TraAccessMode.READ)) - # and cursor - ro_cur = ro_transaction.cursor() - - cur.execute('insert into country values ('Oz','Crowns') - con.commit() # commits main transaction - - # Read data created by main transaction from second one - ro_cur.execute("select * from COUNTRY where COUNTRY = `Oz`") - print(ro_cur.fetchall()) - - # Insert more data, but don't commit - cur.execute('insert into country values ('Barsoom','XXX') - - # Read data created by main transaction from second one - ro_cur.execute("select * from COUNTRY where COUNTRY = `Barsoom`") - print(ro_cur.fetchall()) - -``` - - - - -### Distributed Transactions - -Distributed transactions are transactions that span multiple databases. -Firebird-driver provides this Firebird feature through `.DistributedTransactionManager` -class. Instances of this class must be created manually, and managed transactions -are fully independent from all other transactions, main or secondary, of member connections. - -Similarly to `.TransactionManager`, distributed transactions are managed -through `~.DistributedTransactionManager.begin()`, -`~.DistributedTransactionManager.savepoint()`, `~.DistributedTransactionManager.commit()` -and `~.DistributedTransactionManager.rollback()` methods. -Additionally, `.DistributedTransactionManager` exposes method -`~.DistributedTransactionManager.prepare()` that explicitly initiates the -first phase of `Two-Phase Commit Protocol`. Transaction parameters are defined -similarly to `.TransactionManager` using `~.DistributedTransactionManager.default_tpb` -or as optional parameter to `~.DistributedTransactionManager.begin()` call. - -SQL statements that should belong to context of distributed transaction are -executed via `.Cursor` instances aquired through `.DistributedTransactionManager.cursor()` -method, or calling `.DistributedTransactionManager.execute_immediate()` method. - -!!! note - - Because `.Cursor` instances can belong to only one `.Connection`, the - `~.DistributedTransactionManager.cursor()` method has mandatory parameter - `connection`, to specify to which member connection cursor should belong. - - The `~.DistributedTransactionManager.execute_immediate()` method operates - on **all** databases in *group*. - -**Example program:** - -```python -from firebird.driver import create_database, DistributedTransactionManager - -# First database -con1 = create_database('db1.fdb', user='SYSDBA', password='masterkey') -con1.execute_immediate("recreate table T (PK integer, C1 integer)") -con1.commit() - -# Second database -con2 = create_database('db2.fdb', user='SYSDBA', password='masterkey') -con2.execute_immediate("recreate table T (PK integer, C1 integer)") -con2.commit() - -# Create distributed transaction manager -dt = DistributedTransactionManager((con1,con2)) - -# Prepare cursors for each connection -dc1 = dt.cursor(con1) -dc2 = dt.cursor(con2) - -# Connection cursors to check content of databases -q = 'select * from T order by pk' - -cc1 = con1.cursor() -p1 = cc1.prep(q) - -cc2 = con2.cursor() -p2 = cc2.prep(q) - -print("Distributed transaction: COMMIT") -# =============================== -dc1.execute('insert into t (pk) values (1)') -dc2.execute('insert into t (pk) values (1)') -dt.commit() - -# check it -con1.commit() -cc1.execute(p1) -print('db1:', cc1.fetchall()) -con2.commit() -cc2.execute(p2) -print('db2:', cc2.fetchall()) - -print("Distributed transaction: PREPARE + COMMIT") -# ========================================= -dc1.execute('insert into t (pk) values (2)') -dc2.execute('insert into t (pk) values (2)') -dt.prepare() -dt.commit() - -# check it -con1.commit() -cc1.execute(p1) -print('db1:', cc1.fetchall()) -con2.commit() -cc2.execute(p2) -print('db2:', cc2.fetchall()) - -print("Distributed transaction: SAVEPOINT + ROLLBACK to it") -# =================================================== -dc1.execute('insert into t (pk) values (3)') -dt.savepoint('CG_SAVEPOINT') -dc2.execute('insert into t (pk) values (3)') -dt.rollback(savepoint='CG_SAVEPOINT') - -# check it - via group cursors, as transaction is still active -dc1.execute(q) -print('db1:', dc1.fetchall()) -dc2.execute(q) -print('db2:', dc2.fetchall()) - -print("Distributed transaction: ROLLBACK") -# ================================= -dt.rollback() - -# check it -con1.commit() -cc1.execute(p1) -print('db1:', cc1.fetchall()) -con2.commit() -cc2.execute(p2) -print('db2:', cc2.fetchall()) - -print("Distributed transaction: EXECUTE_IMMEDIATE") -# ========================================== -dt.execute_immediate('insert into t (pk) values (3)') -dt.commit() - -# check it -con1.commit() -cc1.execute(p1) -print('db1:', cc1.fetchall()) -con2.commit() -cc2.execute(p2) -print('db2:', cc2.fetchall()) - -# Finalize -con1.drop_database() -con1.close() -con2.drop_database() -con2.close() - -``` - -Output: - -```text -Distributed transaction: COMMIT -db1: [(1, None)] -db2: [(1, None)] -Distributed transaction: PREPARE + COMMIT -db1: [(1, None), (2, None)] -db2: [(1, None), (2, None)] -Distributed transaction: SAVEPOINT + ROLLBACK to it -db1: [(1, None), (2, None), (3, None)] -db2: [(1, None), (2, None)] -Distributed transaction: ROLLBACK -db1: [(1, None), (2, None)] -db2: [(1, None), (2, None)] -Distributed transaction: EXECUTE_IMMEDIATE -db1: [(1, None), (2, None), (3, None)] -db2: [(1, None), (2, None), (3, None)] - -``` - - - -### Transaction Context Manager - -Firebird-driver provides context manager `~firebird.driver.core.transaction` that allows automatic -transaction management using WITH statement. It can work with -any object that supports `begin()`, `commit()` and `rollback()` methods, i.e. -`.Connection`, `.TransactionManager` or `.DistributedTransactionManager`. - -It starts transaction when WITH block is entered and commits it if no exception -occurs within it, or calls `rollback()` otherwise. Exceptions raised in WITH -block are never suppressed. - -Examples: - -```python -from firebird.driver import connect, transaction, DistributedTransactionManager - -with connect('employee', user='SYSDBA', password='masterkey') as con: - - # Uses default main transaction - with transaction(con): - cur = con.cursor() - cur.execute("insert into T (PK,C1) values (1,'TXT')") - - # Uses separate transaction - with transaction(con.transaction_manager()) as tr: - cur = tr.cursor() - cur.execute("insert into T (PK,C1) values (2,'AAA')") - - # Uses distributed transaction - with connect('employee2', user='SYSDBA', password='masterkey') as con2, - DistributedTransactionManager(con, con2) as dtm: - with transaction(dtm): - cur1 = cg.cursor(con) - cur2 = cg.cursor(con2) - cur1.execute("insert into T (PK,C1) values (3,'Local')") - cur2.execute("insert into T (PK,C1) values (3,'Remote')") - -``` - - -## Database Events - -### What they are -The Firebird engine features a distributed, inter-process communication mechanism based on -messages called `database events`. A database event is a message passed from a trigger or -stored procedure to an application to announce the occurrence of a specified condition or -action, usually a database change such as an insertion, modification, or deletion of a record. -The Firebird event mechanism enables applications to respond to actions and database changes -made by other, concurrently running applications without the need for those applications to -communicate directly with one another, and without incurring the expense of CPU time -required for periodic polling to determine if an event has occurred. - -### Why use them -Anything that can be accomplished with database events can also be implemented using other -techniques, so why bother with events? Since you’ve chosen to write database-centric programs -in Python rather than assembly language, you probably already know the answer to this question, -but let’s illustrate. - -A typical application for database events is the handling of administrative messages. -Suppose you have an administrative message database with a `message's` table, into which -various applications insert timestamped status reports. It may be desirable to react to -these messages in diverse ways, depending on the status they indicate: to ignore them, to -initiate the update of dependent databases upon their arrival, to forward them by e-mail -to a remote administrator, or even to set off an alarm so that on-site administrators will -know a problem has occurred. - -It is undesirable to tightly couple the program whose status is being reported -(the `message producer`) to the program that handles the status reports (the `message handler`). -There are obvious losses of flexibility in doing so. For example, the message producer may -run on a separate machine from the administrative message database and may lack access rights -to the downstream reporting facilities (e.g., network access to the SMTP server, in the case -of forwarded e-mail notifications). Additionally, the actions required to handle status -reports may themselves be time-consuming and error-prone, as in accessing a remote network -to transmit e-mail. - -In the absence of database event support, the message handler would probably be implemented -via `polling`. Polling is simply the repetition of a check for a condition at a specified -interval. In this case, the message handler would check in an infinite loop to see whether -the most recent record in the `messages` table was more recent than the last message it had -handled. If so, it would handle the fresh message(s); if not, it would go to sleep for -a specified interval, then loop. - -The `polling-based` implementation of the message handler is fundamentally flawed. Polling -is a form of [busy-wait](http://www.catb.org/jargon/html/B/busy-wait.html); the check for new messages is performed at the specified interval, -regardless of the actual activity level of the message producers. If the polling interval -is lengthy, messages might not be handled within a reasonable time period after their arrival; -if the polling interval is brief, the message handler program (and there may be many such -programs) will waste a large amount of CPU time on unnecessary checks. - -The database server is necessarily aware of the exact moment when a new message arrives. -Why not let the message handler program request that the database server send it a notification -when a new message arrives? The message handler can then efficiently sleep until the moment -its services are needed. Under this `event-based` scheme, the message handler becomes -aware of new messages at the instant they arrive, yet it does not waste CPU time checking -in vain for new messages when there are none available. - -### How events are exposed - -1. Server Process ("An event just occurred!") - - To notify any interested listeners that a specific event has - occurred, issue the `POST_EVENT` statement from Stored Procedure - or Trigger. The `POST_EVENT` statement has one parameter: the name - of the event to post. In the preceding example of the administrative - message database, `POST_EVENT` might be used from an `after insert` - trigger on the `messages` table, like this: - - ```sql - create trigger trig_messages_handle_insert - for messages - after insert - as - begin - POST_EVENT 'new_message'; - end - - ``` - - !!! note - The physical notification of the client process does not - - occur until the transaction in which the `POST_EVENT` took place is - actually committed. Therefore, multiple events may *conceptually* - occur before the client process is *physically* informed of even one - occurrence. Furthermore, the database engine makes no guarantee that - clients will be informed of events in the same groupings in which they - conceptually occurred. If, within a single transaction, an event named - `event_a` is posted once and an event named `event_b` is posted once, - the client may receive those posts in separate "batches", despite the - fact that they occurred in the same conceptual unit (a single - transaction). This also applies to multiple occurrences of *the same* - event within a single conceptual unit: the physical notifications may - arrive at the client separately. - -1. Client Process ("Send me a message when an event occurs.") - - !!! note - If you don't care about the gory details of event notification, - - skip to the section that describes FDB's Python-level event handling - API. - - The Firebird C client library offers two forms of event notification. - The first form is *synchronous* notification, by way of the function - `isc_wait_for_event()`. This form is admirably simple for a C programmer - to use, but is inappropriate as a basis for FDB's event support, - chiefly because it's not sophisticated enough to serve as the basis for - a comfortable Python-level API. The other form of event notification - offered by the database client library is *asynchronous*, by way of the - functions `isc_que_events()` (note that the name of that function - is misspelled), `isc_cancel_events()`, and others. The details are - as nasty as they are numerous, but the essence of using asynchronous - notification from C is as follows: - - 1. Call `isc_event_block()` to create a formatted binary buffer that will tell - the server which events the client wants to listen for. - 1. Call `isc_que_events()` (passing the buffer created in the previous step) to - inform the server that the client is ready to receive event notifications, and provide - a callback that will be asynchronously invoked when one or more of the registered events occurs. - 1. [The thread that called `isc_que_events()` to initiate event listening must - now do something else.] - 1. When the callback is invoked (the database client library starts a thread dedicated - to this purpose), it can use the `isc_event_counts()` function to determine - how many times each of the registered events has occurred since the last call to - `isc_event_counts()` (if any). - 1. [The callback thread should now "do its thing", which may include communicating with - the thread that called `isc_que_events()`.] - 1. When the callback thread is finished handling an event notification, it must call - `isc_que_events()` again in order to receive future notifications. Future - notifications will invoke the callback again, effectively "looping" the callback - thread back to Step 4. - -### API for Python developers - -The Firebird-driver database event API is comprised of the following: the method -`.Connection.event_collector()` and the class `.EventCollector`. - -Use the `.Connection.event_collector()` method (takes a sequence of string event -names as parameter) to create `.EventCollector` instance, that collects database event -notifications sent from the server for given database. - -!!! important - - To start listening for events it's necessary to call `.EventCollector.begin()` - method or use EventCollector's context manager interface. - -Immediately when `~.EventCollector.begin()` method is called, EventCollector starts -to accumulate notifications of any event that occur within the collector’s internal queue -until the collector is closed either explicitly (via the `~.EventCollector.close()` -method) or implicitly (via garbage collection). - -Notifications about events are aquired through call to `~.EventCollector.wait()` method, -that blocks the calling thread until at least one of the events occurs, or the specified -`timeout` (if any) expires, and returns `None` if the wait timed out, or a dictionary that -maps `event_name -> event_occurrence_count`. - -!!! important - - `.EventCollector` can act as context manager that ensures execution of - `~.EventCollector.begin()` and `~.EventCollector.close()` methods. - It's strongly advised to use the `.EventCollector` with the `with` statement. - -**Example:** - -```python -with connection.event_collector(['event_a', 'event_b']) as collector: - events = collector.wait() - process_events(events) - -``` - -If you want to drop notifications accumulated so far by conduit, call -`.EventCollector.flush()` method. - -**Example program:** - -```python -from firebird.driver import create_database, transaction -import threading -import time - -# Prepare database -con = create_database('event-test', user='SYSDBA', password='masterkey') -with transaction(con): - con.execute_immediate("CREATE TABLE T (PK Integer, C1 Integer)") - con.execute_immediate("""CREATE TRIGGER EVENTS_AU FOR T ACTIVE - BEFORE UPDATE POSITION 0 - AS - BEGIN - if (old.C1 <> new.C1) then - post_event 'c1_updated' ; - END""") - con.execute_immediate("""CREATE TRIGGER EVENTS_AI FOR T ACTIVE - AFTER INSERT POSITION 0 - AS - BEGIN - if (new.c1 = 1) then - post_event 'insert_1' ; - else if (new.c1 = 2) then - post_event 'insert_2' ; - else if (new.c1 = 3) then - post_event 'insert_3' ; - else - post_event 'insert_other' ; - END""") -cur = con.cursor() - -# Utility function -def send_events(command_list): - with transaction(con): - for cmd in command_list: - cur.execute(cmd) - -print("One event") -# ========= -timed_event = threading.Timer(3.0,send_events,args=[["insert into T (PK,C1) values (1,1)",]]) -with con.event_collector(['insert_1']) as events: - timed_event.start() - e = events.wait() -print(e) - -print("Multiple events") -# =============== -cmds = ["insert into T (PK,C1) values (1,1)", - "insert into T (PK,C1) values (1,2)", - "insert into T (PK,C1) values (1,3)", - "insert into T (PK,C1) values (1,1)", - "insert into T (PK,C1) values (1,2)",] -timed_event = threading.Timer(3.0,send_events,args=[cmds]) -with con.event_collector(['insert_1','insert_3']) as events: - timed_event.start() - e = events.wait() -print(e) - -print("20 events") -# ========= -cmds = ["insert into T (PK,C1) values (1,1)", - "insert into T (PK,C1) values (1,2)", - "insert into T (PK,C1) values (1,3)", - "insert into T (PK,C1) values (1,1)", - "insert into T (PK,C1) values (1,2)",] -timed_event = threading.Timer(1.0,send_events,args=[cmds]) -with con.event_collector(['insert_1','A','B','C','D', - 'E','F','G','H','I','J','K','L','M', - 'N','O','P','Q','R','insert_3']) as events: - timed_event.start() - time.sleep(3) - e = events.wait() -print(e) - -print("Flush events") -# ============ -timed_event = threading.Timer(3.0,send_events,args=[["insert into T (PK,C1) values (1,1)",]]) -with con.event_collector(['insert_1']) as events: - send_events(["insert into T (PK,C1) values (1,1)", - "insert into T (PK,C1) values (1,1)"]) - time.sleep(2) - events.flush() - timed_event.start() - e = events.wait() -print(e) - -# Finalize -con.drop_database() -con.close() - -``` - -Output: - -```text -One event -{'insert_1': 1} -Multiple events -{'insert_3': 1, 'insert_1': 2} -20 events -{'A': 0, 'C': 0, 'B': 0, 'E': 0, 'D': 0, 'G': 0, 'insert_1': 2, 'I': 0, 'H': 0, 'K': 0, 'J': 0, 'M': 0, - 'L': 0, 'O': 0, 'N': 0, 'Q': 0, 'P': 0, 'R': 0, 'insert_3': 1, 'F': 0} -Flush events -{'insert_1': 1} - -``` - - - - -## Working with Services - -Database server maintenance tasks such as user management, load monitoring, -and database backup have traditionally been automated by scripting the -command-line tools `gbak`, `gfix`, `gsec`, and `gstat`. - -The API presented to the client programmer by these utilities is inelegant -because they are, after all, command-line tools rather than native components -of the client language. To address this problem, Firebird has a facility called -the `Services API`, which exposes a uniform interface to the administrative -functionality of the traditional command-line tools. - -The native Services API, though consistent, is much lower-level than a Pythonic API. -If the native version were exposed directly, accomplishing a given task would probably -require more Python code than scripting the traditional command-line tools. For this -reason, the firebird-driver presents its own abstraction over the native API. - - -### Services API Connections - -All Services API operations are performed in the context of a `connection` to a specific -database server, represented by the `.Server` class. Similarly to database connections, -firebird-driver provides `.connect_server()` constructor function to create such connections. - -This constructor has one positional and several keyword parameters. - -The value of `server` positional parameter must be one of: - -* name of registered server configuration -* server host name or address - -Keyword parameters are intended to override selected configuration options, or to specify -options that are not configurable. - -A simple server connection is typically established with code such as this: - -```python -from firebird.driver import connect_server - -# Attach to 'embedded' server -srv = connect_server('', user='SYSDBA', password='masterkey') - -# Attach to 'local' server -srv = connect_server('localhost', user='SYSDBA', password='masterkey') - -# Set 'user' and 'password' via configuration -from firebird.driver import driver_config -driver_config.server_defaults.user.value = 'SYSDBA' -driver_config.server_defaults.password.value = 'masterkey' -srv = connect_server('localhost') - -``` - -However, it's recommended to use specific configuration for servers. -It's possible to register servers directly in code like this: - -```python -from firebird.driver import connect_server, driver_config - -# Register Firebird server -srv_cfg = """[main_server] -host = 192.168.0.15 -user = SYSDBA -password = Xyzzy -""" -driver_config.register_server('main_server', srv_cfg) - -# Attach to 'main' server -con = connect('main_server') - -``` - -But more convenient approach is using single configuration file: - -```text -# file: myapp.cfg - -[firebird.driver] -servers = main_server -databases = employee - -[main_server] -host = 192.168.0.15 -user = SYSDBA -password = Xyzzy - -``` - -```python -from firebird.driver import connect_server, driver_config - -driver_config.read('myapp.cfg') - -# Attach to 'main' server -con = connect('main_server') - -``` - -!!! note - - Like database connections, it's important to properly `~Server.close()` them - when you don't need them anymore. - -`.Server` object provides main infrastructure for communication with Firebird server services, -and manages number of objects that provide actual server services: - -* The `.Server.info` property object provides [Server Configuration and State information](usage-guide.md#server-configuration-and-state-information). -* The `.Server.database` property object provides [Database options](usage-guide.md#database-options) and [Database maintenance](usage-guide.md#database-maintenance). -* The `.Server.user` property object provides [User maintenance](usage-guide.md#user-maintenance). -* The `.Server.trace` property object provides management of [Trace sessions](usage-guide.md#trace-sessions). - -!!! info - `.connect_server()` and `.Server` for details. - - -### Text output from Services - -Some services like `.ServerDbServices.backup()` may return significant amount of text. -Rather than return the whole text as single string value by methods that provide access -to these services, firebird-driver isolated the transfer process to separate methods: - -* `~.Server.readline()` - Similar to `file.readline`, returns next line of output from Service. -* `~.Server.readline_timed()` - Like `~.Server.readline()` but with timeout. -* `~.Server.readlines()` - Like `file.readlines`, returns list of output lines. -* Iteration over `.Server` object, because `.Server` has built-in support for [iterator protocol](https://docs.python.org/3/library/stdtypes.html#iterator-types). -* Using `callback` method provided by developer. Each `.Server` method that returns its result - asynchronously accepts an optional parameter `callback`, which must be a function that accepts - one string parameter. This method is then called with each output line coming from service. -* `~.Server.wait()` - Waits for Sevice to finish, ignoring rest of the output it may produce. - -!!! important - - The Firebird server sends text output from services as packets, that could have two forms. - The method for packet construction used for text transfer is controlled by `.Server.mode` - attribute with next possible values: - - 1. `.SrvInfoCode.LINE` : A single line of text. - 2. `.SrvInfoCode.TO_EOF` : A block of text up to specified (buffer) size. - - Both methods have specific pros and cons: - - 1. `~.SrvInfoCode.LINE` means more roundtrips and thus slower transfer of service output, - but each line is sent to client immediately when it's available. - 2. `~.SrvInfoCode.TO_EOF` means fewer roundtrips so large output is transferred quickly, - but service output is not sent until the transfer buffer is not full, or service stops. - - **The default mode is** `~.SrvInfoCode.TO_EOF` **with 64K buffer.** - -!!! warning - - Until output is not fully fetched from service, any attempt to start another asynchronous - service will fail with exception! This constraint is set by Firebird Service API. - - You may check the status of asynchronous Services using `.Server.is_running()` method. - - In cases when you're not interested in output produced by Service, call `~.Server.wait()` - to wait for service to complete. - -!!! important - - Normally, requesting output with `~.Server.readline()` blocks until any output is - available from server. Bacuse this method is used by iteration over `.Server` and - `~.Server.readlines()` method, they will block as well. Most services produce output - continuously and without (much) delay, so this is usually not a problem. However, some - services (eg trace) can produce output at significantly slower intervals (if at all), - which complicates the creation of responsive applications. In this case, it is necessary - to use the `~.Server.readline_timed()` method, which allows you to limit the waiting - time for the output. - -**Examples:** - -```python -from firebird.driver import connect_server -with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - print("Fetch materialized") - print("==================") - print("Start backup") - srv.database.backup(database='employee', backup='employee.fbk') - print("srv.running is", srv.isrunning()) - report = srv.readlines() - print(f"{len(report)} lines returned") - print("First 5 lines from output:") - for i in xrange(5): - print(i,report[i]) - print("srv.running is", srv.isrunning()) - print() - print("Iterate over result") - print("===================") - srv.database.backup(database='employee', backup='employee.fbk') - output = [] - for line in srv: - output.append(line) - print(f"{len(output)} lines returned") - print("Last 5 lines from output:") - for line in output[-5:]: - print(line) - print() - print("Callback") - print("========") - - output = [] - - # Callback function - def fetchline(line): - output.append(line) - - srv.database.backup(database='employee', backup='employee.fbk', callback=fetchline) - print(f"{len(output)} lines returned") - print("Last 5 lines from output:") - for line in output[-5:]: - print(line) - -``` - -Output: - -```text -Fetch materialized -================== -Start backup -svc.running is True -558 lines returned -First 5 lines from output: -0 gbak:readied database employee for backup -1 gbak:creating file employee.fbk -2 gbak:starting transaction -3 gbak:database employee has a page size of 4096 bytes. -4 gbak:writing domains -svc.running is False - -Iterate over result -=================== -558 lines returned -Last 5 lines from output: -gbak:writing referential constraints -gbak:writing check constraints -gbak:writing SQL roles -gbak:writing names mapping -gbak:closing file, committing, and finishing. 74752 bytes written - -Callback -======== -558 lines returned -Last 5 lines from output: -gbak:writing referential constraints -gbak:writing check constraints -gbak:writing SQL roles -gbak:writing names mapping -gbak:closing file, committing, and finishing. 74752 bytes written - -``` - -### Server Configuration and State information - -!!! important - - Because the scope and type of service information depends on the version of the Firebird - server, this information is made available through a separate class - `.ServerInfoProvider`. The `.Server.info` property provides access to - instance of `.ServerInfoProvider` or it's **ancestor** class according to attached - Firebird server version. - -`.ServerInfoProvider` methods and properties: - -* `~.ServerInfoProvider.get_log()` - Request the contents of the server’s log file (`firebird.log`). - - This method is so-called `Async service` that only initiates log transfer. Actual log - content could be read by one from many methods for [text output from Services](usage-guide.md#text-output-from-services) that - `.Server` provides . - -* `~.ServerInfoProvider.version` - Returns Firebird server version as SEMVER string. - -* `~.ServerInfoProvider.engine_version` - Firebird server version as . float value. - -* `~.ServerInfoProvider.manager_version` - Firebird service manager version. - -* `~.ServerInfoProvider.architecture` - Firebird server implementation description. - -* `~.ServerInfoProvider.home_directory` - Firebird server home directory. - -* `~.ServerInfoProvider.security_database` - Security database. - -* `~.ServerInfoProvider.lock_directory` - Directory with lock file(s). - -* `~.ServerInfoProvider.message_directory` - Directory with message file(s). - -* `~.ServerInfoProvider.capabilities` - Firebird server capabilities (as `.ServerCapability` flags). - -* `~.ServerInfoProvider.connection_count` - Current number of database attachments. - -* `~.ServerInfoProvider.attached_databases` - List of attached databases. - -**Example:** - -```python -from firebird.driver import driver_config, connect, connect_server - -srv_cfg = """[local] -host = localhost -user = SYSDBA -password = masterkey -""" -driver_config.register_server('local', srv_cfg) -db_cfg = """[employee] -server = local -database = employee.fdb -protocol = inet -""" -driver_config.register_database('employee', db_cfg) -with connect('employee', user='SYSDBA', password='masterkey'), connect_server('local', user='SYSDBA', password='masterkey') as srv: - print(f'{srv.info.version=}') - print(f'{srv.info.engine_version=}') - print(f'{srv.info.manager_version=}') - print(f'{srv.info.architecture=}') - print(f'{srv.info.home_directory=}') - print(f'{srv.info.security_database=}') - print(f'{srv.info.lock_directory=}') - print(f'{srv.info.message_directory=}') - print(f'{srv.info.capabilities=!s}') - print(f'{srv.info.connection_count=}') - print(f'{srv.info.attached_databases=}') - -``` - -Sample output for 64-bit Linux Firebird 4.0 Beta 2: - -```text -srv.info.version='4.0.0.1963' -srv.info.engine_version=4.0 -srv.info.manager_version=2 -srv.info.architecture='Firebird/Linux/AMD/Intel/x64' -srv.info.home_directory='/opt/firebird/' -srv.info.security_database='/opt/firebird/security4.fdb' -srv.info.lock_directory='/tmp/firebird/' -srv.info.message_directory='/opt/firebird/' -srv.info.capabilities=ServerCapability.REMOTE_HOP|MULTI_CLIENT -srv.info.connection_count=1 -srv.info.attached_databases=['/opt/firebird/examples/empbuild/employee.fdb'] - -``` - -### Database options - -Database options could be set using `.ServerDbServices` instance accessible via -`.Server.database` property. - -* `~.ServerDbServices.set_default_cache_size()` - Sets individual page cache size for database. - - ```python - >>> from firebird.driver import connect_server - >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - >>> srv.database.set_default_cache_size(database='employee.fdb', size=5000) - - ``` - -* `~.ServerDbServices.set_sweep_interval()` - Sets database sweep interval. - - ```python - >>> from firebird.driver import connect_server - >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - >>> srv.database.set_sweep_interval(database='employee.fdb', interval=100000) - - ``` - -* `~.ServerDbServices.set_space_reservation()` - Sets space reservation option for database. - - ```python - >>> from firebird.driver import connect_server, DbSpaceReservation - >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - >>> srv.database.set_space_reservation(database='employee.fdb', mode=DbSpaceReservation.USE_FULL) - - ``` - -* `~.ServerDbServices.set_write_mode()` - Sets database write mode (SYNC/ASYNC). - - ```python - >>> from firebird.driver import connect_server, DbWriteMode - >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - >>> srv.database.set_write_mode(database='employee.fdb', mode=DbWriteMode.ASYNC) - - ``` - -* `~.ServerDbServices.set_access_mode()` - Sets database access mode (R/W or R/O). - - ```python - >>> from firebird.driver import connect_server, DbAccessMode - >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - >>> srv.database.set_access_mode(database='employee.fdb', mode=DbAccessMode.READ_ONLY) - - ``` - -* `~.ServerDbServices.set_sql_dialect()` - Sets database SQL dialect. - - !!! warning - - Changing SQL dialect on existing database is not recommended. Only newly created - database objects would respect new dialect setting, while objects created with - previous dialect remain unchanged. That may have dire consequences. - - ```python - >>> from firebird.driver import connect_server - >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - >>> srv.database.set_sql_dialect(database='employee.fdb', dialect=1) - - ``` - -* `~.ServerDbServices.no_linger()` - Sets one-off override for database linger. - - ```python - >>> from firebird.driver import connect_server - >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - >>> srv.database.no_linger(database='employee.fdb') - - ``` - - -### Database maintenance - -!!! important - - Because available database-related actions depends on the version of the Firebird - server, they are made available through a separate class `.ServerDbServices`. - The `.Server.database` property provides access to instance of `.ServerDbServices` or - it's **ancestor** class according to attached Firebird server version. - -* `~.ServerDbServices3.get_statistics()` - Returns database statistics produced by gstat - utility. - - This method is so-called `Async service` that only initiates report processing. Actual - report content could be read by one from many methods for [text output from Services](usage-guide.md#text-output-from-services) that - `.Server` provides . - - ```python - from firebird.driver import connect_server, SrvStatFlag - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.get_statistics(database='employee.fdb', - flags=SrvStatFlag.DATA_PAGES | SrvStatFlag.RECORD_VERSIONS), - tables=['EMPLOYEE','PROJECT']) - stats = srv.readlines() - - ``` - -* `~.ServerDbServices3.backup()` - Performs logical (GBAK) database backup. - - This method is so-called `Async service` that only initiates the backup process. Output - from gbak could be read by one from many methods for [text output from Services](usage-guide.md#text-output-from-services) that - `.Server` provides . - - ```python - from firebird.driver import connect_server, SrvBackupFlag - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.backup(database='employee.fdb', - backup='/backup/employee.fbk', - flags=SrvBackupFlag.IGNORE_CHECKSUMS | SrvBackupFlag.NO_GARBAGE_COLLECT, - stats='TD', verbose=True) - report = srv.readlines() - - ``` - -* `~.ServerDbServices3.local_backup()` - Performs logical (GBAK) database backup into local byte - stream. - - ```python - from firebird.driver import connect_server, SrvBackupFlag - f = open('/backup/employee.fbk',mode='wb') - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.local_backup(database='employee.fdb', backup_stream=f, - flags=SrvBackupFlag.IGNORE_CHECKSUMS | SrvBackupFlag.NO_GARBAGE_COLLECT) - f.close() - - ``` - -* `~.ServerDbServices3.restore()` - Performs database restore from logical (GBAK) backup. - - This method is so-called `Async service` that only initiates the restore process. Output - from gbak could be read by one from many methods for [text output from Services](usage-guide.md#text-output-from-services) that - `.Server` provides . - - ```python - from firebird.driver import connect_server, SrvRestoreFlag - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.restore(backup='/backup/employee.fbk', - database='/data/employee.fdb', - flags=SrvRestoreFlag.REPLACE, - stats='TD', verbose=True, page_size=8192) - report = srv.readlines() - - ``` - -* `~.ServerDbServices3.local_restore()` - Performs database restore from logical (GBAK) backup - stored in local byte stream. - - ```python - from firebird.driver import connect_server, SrvRestoreFlag - f = open('/backup/employee.fbk',mode='rb') - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.local_restore(backup_stream=f, database='/data/employee.fdb', - flags=SrvRestoreFlag.REPLACE, page_size=8192) - f.close() - - ``` - -* `~.ServerDbServices3.nbackup()` - Performs physical (NBACKUP) database backup. - - ```python - from firebird.driver import connect_server - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.nbackup(database='employee.fdb', backup='/backup/employee.bkp1', level=1) - - ``` - -* `~.ServerDbServices3.nrestore()` - Performs restore from physical (NBACKUP) database - backup. - - ```python - from firebird.driver import connect_server - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.nrestore(backups=['/backup/employee.bkp0', '/backup/employee.bkp1'], - database='/data/employee.fdb') - - ``` - -* `~.ServerDbServices3.shutdown()` - Database shutdown. - - ```python - from firebird.driver import connect_server, ShutdownMode, ShutdownMethod - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.shutdown(database='employee.fdb', mode=ShutdownMode.SINGLE, - method=ShutdownMethod.FORCED, timeout=10) - - ``` - -* `~.ServerDbServices3.bring_online()` - Bring previously shut down database back online. - - ```python - from firebird.driver import connect_server, OnlineMode - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.bring_online(database='employee.fdb', mode=OnlineMode.MULTI) - - ``` - -* `~.ServerDbServices3.sweep()` - Performs database sweep operation. - - ```python - from firebird.driver import connect_server - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.sweep(database='employee.fdb') - - ``` - -* `~.ServerDbServices3.validate()` - Performs database validation. - - This method is so-called `Async service` that only initiates the validation process. Output - from validation could be read by one from many methods for [text output from Services](usage-guide.md#text-output-from-services) that - `.Server` provides . - - ```python - from firebird.driver import connect_server - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.validate(database='employee.fdb') - report = srv.readlines() - - ``` - -* `~.ServerDbServices3.repair()` - Performs database repair operation. - - ```python - from firebird.driver import connect_server, SrvRepairFlag - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - srv.database.repair(database='employee.fdb', - flags=SrvRepairFlag.REPAIR | SrvRepairFlag.KILL_SHADOWS) - - ``` - -* `~.ServerDbServices3.get_limbo_transaction_ids()` - Returns list of transactions in limbo. - -* `~.ServerDbServices3.commit_limbo_transaction()` - Resolves limbo transaction with commit. - -* `~.ServerDbServices3.rollback_limbo_transaction()` - Resolves limbo transaction with rollback. - -* `~.ServerDbServices.nfix_database` - Fixup database after filesystem copy. - -* `~.ServerDbServices.set_replica_mode` - Manage replica database. - - -### User maintenance - -!!! important - - Because user maintenance functionality may depend on the version of the Firebird - server, this functionality is made available through a separate class - `.ServerUserServices`. The `.Server.user` property provides access to - instance of `.ServerUserServices` or it's **ancestor** class according to attached - Firebird server version. - -!!! tip - - Since Firebird 2.5 you can use SQL commands (CREATE/ALTER/DROP USER) to manage users in - a security database from a regular database attachment. - - The SQL set of DDL commands for managing user accounts has been further enhanced in Firebird 3, - thus improving the DDL capabilities in a way that exceeds capabilities of user management services. - -* `~.ServerUserServices.get_all()` - Returns information about all users. - -* `~.ServerUserServices.get()` - Returns information about specified users. - -* `~.ServerUserServices.add()` - Add new user. - -* `~.ServerUserServices.update()` - Update user information. - -* `~.ServerUserServices.delete()` - Delete user. - -* `~.ServerUserServices.exists()` - Returns True if user exists. - - -### Trace sessions - -!!! important - - Because trace functionality may depend on the version of the Firebird server, this - functionality is made available through a separate class `.ServerTraceServices`. - The `.Server.trace` property provides access to instance of `.ServerTraceServices` or - its **ancestor** class according to attached Firebird server version. - -* `.ServerTraceServices.start()` - Start new trace session. Requires trace `configuration` and returns `Session ID`. - - This method is so-called `Async service` that only starts the trace session. Output - from trace session could be read by one from many methods for [text output from Services](usage-guide.md#text-output-from-services) - that `.Server` provides . - - ```python - from firebird.driver import connect_server - - trace_config = """database = %[\\/]employee.fdb - { - enabled = true - log_statement_finish = true - print_plan = true - include_filter = %%SELECT%% - exclude_filter = %%RDB$%% - time_threshold = 0 - max_sql_length = 2048 - } - """ - - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - trace_id = srv.trace.start(trace_config,'test_trace_1') - trace_log = [] - # Get first 10 lines of trace output - for i in range(10): - trace_log.append(srv.readline()) - # Stop trace session - # Because trace session blocks the connection, we need another one to stop trace session! - with connect_server('localhost', user='SYSDBA', password='masterkey') as srv_aux: - srv_aux.trace.stop(trace_id) - - ``` - -* `.ServerTraceServices.stop()` - Stop trace session. - -* `.ServerTraceServices.suspend()` - Suspend trace session. - -* `.ServerTraceServices.resume()` - Resume trace session. - -* `.ServerTraceServices.sessions` - Dictionary with active trace sessions. The key is session ID, value is `.TraceSession` instance. - - - -## Logging driver activities - -The firebird-driver supports [context-based logging system](https://firebird-base.readthedocs.io/en/latest/logging/) -provided by [firebird-base](https://firebird-base.rtfd.io) package through use of `~firebird.base.logging.LoggingIdMixin`. - -Classes that use `~firebird.base.logging.LoggingIdMixin`: - -* `.Connection` - Internally used objects have `_logging_id_` set to 'Transaction.Main', - 'Transaction.Query' and 'Cursor.internal'. The log context is not defined. -* `.TransactionManager` - The `_logging_id_` is set to 'Transaction'. The - `~.TransactionManager.log_context()` is the `.Connection`. -* `.DistributedTransactionManager` - The `_logging_id_` is set to 'DTransaction'. The - `~.DistributedTransactionManager.log_context()` is `~firebird.base.types.UNDEFINED`. -* `.Statement` - The `~.Statement.log_context()` is `.Connection`. -* `.BlobReader` - The `~.Statement.log_context()` is the owning object or `~firebird.base.types.UNDEFINED`. -* `.Cursor` - The `~.Cursor.log_context()` is `.Connection`. -* `.Server` - The log context is not defined. - -**Example:** - -```python -import logging -from firebird.base.logging import get_logger, LogLevel -from firebird.driver import connect, driver_config - -# Helper function -def execute(cur: Cursor, cmd: str) -> None: - get_logger(cur).debug(f"Execute [{cmd=}]") - cur.execute(cmd) - -# Basic Python logging configuration -sh = logging.StreamHandler() -sh.setFormatter(logging.Formatter('%(levelname)-10s: [%(agent)s][%(context)s] %(message)s')) -logger = logging.getLogger() -logger.addHandler(sh) -logger.setLevel(LogLevel.DEBUG) - -# Firebird driver configuration -srv_cfg = """[local] -host = localhost -user = SYSDBA -password = masterkey -""" -driver_config.register_server('local', srv_cfg) -db_cfg = """[employee] -server = local -database = employee.fdb -protocol = inet -""" -driver_config.register_database('employee', db_cfg) - -print("Default logging ids") -with connect('employee') as con: - con_log = get_logger(con) - con_log.info('Start') - cur1 = con.cursor() - cur2 = con.cursor() - execute(cur1, 'select * from country') - execute(cur2, 'select * from project') - con_log.info('Stop') - -print("Custom logging ids") -with connect('employee') as con: - con._logging_id_ = 'employee-1' - con_log = get_logger(con) - con_log.info('Start') - cur1 = con.cursor() - cur1._logging_id_ = 'cursor-1' - cur2 = con.cursor() - cur2._logging_id_ = 'cursor-2' - execute(cur1, 'select * from country') - execute(cur2, 'select * from project') - con_log.info('Stop') - -``` - -Output: - -```text -Default logging ids -INFO : [Connection][UNDEFINED] Start -DEBUG : [Cursor][Connection] Execute [cmd='select * from country'] -DEBUG : [Cursor][Connection] Execute [cmd='select * from project'] -INFO : [Connection][UNDEFINED] Stop -Custom logging ids -INFO : [employee-1][UNDEFINED] Start -DEBUG : [cursor-1][employee-1] Execute [cmd='select * from country'] -DEBUG : [cursor-2][employee-1] Execute [cmd='select * from project'] -INFO : [employee-1][UNDEFINED] Stop - -``` -You can also trace the driver activities using [trace/audit for class instances](https://firebird-base.readthedocs.io/en/latest/trace/) -provided by [firebird-base](https://firebird-base.rtfd.io) package. - -**Example:** - -```python -import logging -from firebird.base.logging import get_logger, LogLevel -from firebird.base.trace import trace_manager, add_trace, trace_object, traced, TraceFlag -from firebird.driver import connect, driver_config -from firebird.driver.core import TransactionManager - -# Helper function -def execute(cur: Cursor, cmd: str) -> None: - cur.execute(cmd) - -# Basic Python logging configuration -sh = logging.StreamHandler() -sh.setFormatter(logging.Formatter('%(levelname)-10s: [%(agent)s][%(context)s] %(message)s')) -logger = logging.getLogger() -logger.addHandler(sh) -logger.setLevel(LogLevel.DEBUG) - -# Firebird driver configuration -srv_cfg = """[local] -host = localhost -user = SYSDBA -password = masterkey -""" -driver_config.register_server('local', srv_cfg) -db_cfg = """[employee] -server = local -database = employee.fdb -protocol = inet -""" -driver_config.register_database('employee', db_cfg) - -# Trace configuration -# First: register classes and methods that could be traced -trace_manager.register(Connection) -add_trace(Connection, 'close', traced) -trace_manager.register(TransactionManager) -add_trace(TransactionManager, 'begin', traced) -add_trace(TransactionManager, 'commit', traced) -add_trace(TransactionManager, 'rollback', traced) -trace_manager.register(Cursor) -add_trace(Cursor, 'execute', traced) -add_trace(Cursor, 'close', traced) -# Activate trace/audit -trace_manager.trace |= (TraceFlag.ACTIVE | TraceFlag.BEFORE | TraceFlag.AFTER | TraceFlag.FAIL) - -# Traced code -with connect('employee') as con: - trace_object(con) - trace_object(con.main_transaction) - con._logging_id_ = 'employee-1' - cur1 = con.cursor() - trace_object(cur1) - cur1._logging_id_ = 'cursor-1' - cur2 = con.cursor() - trace_object(cur2) - cur2._logging_id_ = 'cursor-2' - execute(cur1, 'select * from country') - execute(cur2, 'select * from project') - con.commit() - -``` - -Sample output: - -```text -DEBUG : [cursor-1][employee-1] >>> execute(operation='select * from country', parameters=None) -DEBUG : [Transaction.Main][employee-1] >>> begin(tpb=None) -DEBUG : [Transaction.Main][employee-1] <<< begin[0.00672] -DEBUG : [cursor-1][employee-1] >>> close() -DEBUG : [cursor-1][employee-1] <<< close[0.00004] -DEBUG : [cursor-1][employee-1] <<< execute[0.01119] Result: cursor-1 -DEBUG : [cursor-2][employee-1] >>> execute(operation='select * from project', parameters=None) -DEBUG : [cursor-2][employee-1] >>> close() -DEBUG : [cursor-2][employee-1] <<< close[0.00002] -DEBUG : [cursor-2][employee-1] <<< execute[0.00352] Result: cursor-2 -DEBUG : [Transaction.Main][employee-1] >>> commit(retaining=False) -DEBUG : [cursor-1][employee-1] >>> close() -DEBUG : [cursor-1][employee-1] <<< close[0.00017] -DEBUG : [cursor-2][employee-1] >>> close() -DEBUG : [cursor-2][employee-1] <<< close[0.00012] -DEBUG : [Transaction.Main][employee-1] <<< commit[0.00225] -DEBUG : [employee-1][UNDEFINED] >>> close() -DEBUG : [employee-1][UNDEFINED] <<< close[0.00764] - - -``` -If you will remove the `con.commit()` from the example above, the output will change to: - -```text -DEBUG : [cursor-1][employee-1] >>> execute(operation='select * from country', parameters=None) -DEBUG : [Transaction.Main][employee-1] >>> begin(tpb=None) -DEBUG : [Transaction.Main][employee-1] <<< begin[0.00338] -DEBUG : [cursor-1][employee-1] >>> close() -DEBUG : [cursor-1][employee-1] <<< close[0.00003] -DEBUG : [cursor-1][employee-1] <<< execute[0.00730] Result: cursor-1 -DEBUG : [cursor-2][employee-1] >>> execute(operation='select * from project', parameters=None) -DEBUG : [cursor-2][employee-1] >>> close() -DEBUG : [cursor-2][employee-1] <<< close[0.00003] -DEBUG : [cursor-2][employee-1] <<< execute[0.00345] Result: cursor-2 -DEBUG : [employee-1][UNDEFINED] >>> close() -DEBUG : [Transaction.Main][employee-1] >>> rollback(retaining=False, savepoint=None) -DEBUG : [cursor-1][employee-1] >>> close() -DEBUG : [cursor-1][employee-1] <<< close[0.00016] -DEBUG : [cursor-2][employee-1] >>> close() -DEBUG : [cursor-2][employee-1] <<< close[0.00014] -DEBUG : [Transaction.Main][employee-1] <<< rollback[0.00171] -DEBUG : [employee-1][UNDEFINED] <<< close[0.01001] - - -``` - - - - -## Driver hooks - -The firebird-driver uses [hook manager](https://firebird-base.readthedocs.io/en/latest/hooks/) from [firebird-base](https://firebird-base.rtfd.io) package -to provide internal notification mechanism that allows installation of custom hooks into -certain driver tasks. - -Driver hooks are divided into several types exposed as enums in `firebird.driver.hooks` module. - -### APIHook - -`.APIHook.LOADED` - This hook is invoked once when instance of `.FirebirdAPI` is created. -It could be used for additional initialization tasks that require Firebird API, or to manipulate -the FirebirdAPI instance itself before its use. - -Hook routine must have signature: `hook_func(api: FirebirdAPI) -> None`. Any value returned -by hook is ignored. - -### ConnectionHook - -* `.ConnectionHook.ATTACH_REQUEST` - - This hook is invoked after all parameters are preprocessed and before `.Connection` is created. - - Hook routine must have signature: `hook_func(dsn: str, dpb: bytes) -> Optional[Connection]` - where `dpb` is Database Parameter Buffer that would be used to create the attachment to the - database defined by `dsn`. It may return `.Connection` (or subclass) instance or `None`. - - First instance returned by any hook of this type will become the return value of caller function - and other hooks of the same type are not invoked. - -* `.ConnectionHook.ATTACHED` - - This hook is invoked just before `.Connection` (or subclass) instance is returned to the client - application. - - Hook routine must have signature: `hook_func(con: Connection) -> None`. - -* `.ConnectionHook.DETACH_REQUEST` - - This hook is invoked before connection is closed. - - Hook must have signature: `hook_func(con: Connection) -> None`. - - If any hook function returns True, connection is not closed. - -* `.ConnectionHook.CLOSED` - - This hook is invoked after connection is closed. - - Hook routine must have signature: `hook_func(con: Connection) -> None`. - -* `.ConnectionHook.DROPPED` - - This hook is invoked after database is dropped (and connection is closed). - - Hook routine must have signature: `hook_func(con: Connection) -> None`. - -### ServerHook - -* `.ServerHook.ATTACHED` - - This hook is invoked before `.Server` instance is returned. - - Hook routine must have signature: `hook_func(srv: Server) -> None`. - - - -[DDL]: http://en.wikipedia.org/wiki/Data_Definition_Language -[DML]: http://en.wikipedia.org/wiki/Data_Manipulation_Language -[Firebird SAVEPOINTs]: http://www.firebirdsql.org/refdocs/langrefupd15-savepoint.html -[Firebird Book]: https://www.ibphoenix.com/products/books/firebird_book -[busy-wait]: http://www.catb.org/jargon/html/B/busy-wait.html -[Visitor Pattern]: http://en.wikipedia.org/wiki/Visitor_pattern -[setuptools]: https://pypi.org/project/setuptools/ -[PYPI]: https://pypi.org/ -[ctypes]: http://docs.python.org/library/ctypes.html -[pip]: https://pypi.org/project/pip/ -[firebird-base]: https://firebird-base.rtfd.io diff --git a/docs/docs/usage-guide/configuration.md b/docs/docs/usage-guide/configuration.md new file mode 100644 index 0000000..a6c0b08 --- /dev/null +++ b/docs/docs/usage-guide/configuration.md @@ -0,0 +1,57 @@ +# Configuration + +The driver uses configuration built on top of [configuration system](https://firebird-base.readthedocs.io/en/latest/config/) +provided by [firebird-base](https://firebird-base.rtfd.io) package. In addition to global settings, the configuration +also includes the definition of connection parameters to Firebird servers and databases. + +The default configuration connects to embedded server using direct/local connection method. +To access remote servers and databases (or local ones through remote protocols), it's +necessary to adjust default configuration, or `register` them in configuration manager. + +You can manipulate the configuration objects directly, or load configuration from files or +strings (in `.ini-style` `configparser` format). + +## The 'driver_config' object + +The global `.driver_config` object holds all configurable driver parameters, and access +configuration parameters for registered Firebird servers and databases. + +In initial state, all parameters have default values and there are no registered servers +and databases. You can set individual parameter values directly, or you can set multiple +parameters (including registered servers and databases) at once by loading them from +configuration string, dict or file(s). + +!!! important + + If you want to use specific Firebird client library, you must set the value of + `.DriverConfig.fb_client_library` configuration option **before** your application + calls any from following functions: `.connect()`, `~firebird.driver.core.create_database()`, + `.connect_server()`, `.load_api()` or `.get_api()`. + +!!! info + + `.DriverConfig` for list of available methods and parameters. + +## Server and database configuration + +Firebird provides ever-increasing list of parameter options for database and server connections. +To keep the Python API clean and manageable, the `firebird-driver` uses server and database +configuration objects instead function parameters to specify values for almost all such options. +Connection functions then provide a name parameter that can refer to particular server / database +or configuration, and few keyword parameters to specify / override selected options. + +!!! important + + The configuration objects does not allow specification of next options: + + - set database encryption callback (for technical reasons) + - set db_key scope (for security reasons) + - disable garbage collection (for security reasons) + - disable database triggers (for security reasons) + - allow overwrite of existing database with newly created database (for security reasons) + + These options could be specified only as keyword arguments in appropriate functions. + +!!! info + + `.ServerConfig` and `.DatabaseConfig` for list of available methods and parameters. diff --git a/docs/docs/usage-guide/data-handling-and-conversions.md b/docs/docs/usage-guide/data-handling-and-conversions.md new file mode 100644 index 0000000..267421c --- /dev/null +++ b/docs/docs/usage-guide/data-handling-and-conversions.md @@ -0,0 +1,319 @@ +# Data handling and conversions + + +## Implicit Conversion of Input Parameters from Strings + +The Firebird database engine treats most SQL data types in a weakly typed fashion: +the engine may attempt to convert the raw value to a different type, as appropriate +for the current context. For instance, the SQL expressions `123` (integer) and `‘123’` +(string) are treated equivalently when the value is to be inserted into an `integer` +field; the same applies when `‘123’` and `123` are to be inserted into a `varchar` field. + +This weak typing model is quite unlike Python’s dynamic yet strong typing. Although +weak typing is regarded with suspicion by most experienced Python programmers, the +database engine is in certain situations so aggressive about its typing model that +firebird-driver must compromise in order to remain an elegant means of programming +the database engine. + +An example is the handling of “magic values” for date and time fields. The database +engine interprets certain string values such as `‘yesterday’` and `‘now’` as having +special meaning in a date/time context. If firebird-driver did not accept strings as +the values of parameters destined for storage in date/time fields, the resulting code +would be awkward. Consider the difference between the two Python snippets below, which +insert a row containing an integer and a timestamp into a table defined with the following +DDL statement: + +```sql +create table test_table (i integer, t timestamp) + +``` + +```python +i = 1 +t = 'now' +sqlWithMagicValues = f"insert into test_table (i, t) values (?, '{t}')" +cur.execute(sqlWithMagicValues, (i,)) + +``` + +```python +i = 1 +t = 'now' +cur.execute("insert into test_table (i, t) values (?, ?)", (i, t)) + +``` + +If firebird-driver did not support weak parameter typing, string parameters that +the database engine is to interpret as “magic values” would have to be rolled into +the SQL statement in a separate operation from the binding of the rest of the parameters, +as in the first Python snippet above. Implicit conversion of parameter values from +strings allows the consistency evident in the second snippet, which is both more +readable and more general. + +!!! note + + It should be noted that firebird-driver does not perform the conversion from string + itself. Instead, it passes that responsibility to the database engine by changing + the parameter metadata structure dynamically at the last moment, then restoring + the original state of the metadata structure after the database engine has performed + the conversion. + +A secondary benefit is that when one uses firebird-driver to import large amounts +of data from flat files into the database, the incoming values need not necessarily +be converted to their proper Python types before being passed to the database engine. +Eliminating this intermediate step may accelerate the import process considerably, +although other factors such as the chosen connection protocol and the deactivation +of indexes during the import are more consequential. For bulk import tasks, the +database engine’s external tables also deserve consideration. External tables can +be used to suck semi-structured data from flat files directly into the relational +database without the intervention of an ad hoc conversion program. + + +## Automatic conversion from/to Unicode + +In Firebird, every `CHAR`, `VARCHAR` or textual `BLOB` field can (or, better: must) +have a `character set` assigned. While it's possible to define single character set +for whole database, it's also possible to define different character set for each +textual field. This information is used to correctly store the bytes that make up +the character string, and together with collation information (that defines the sort +ordering and uppercase conversions for a string) is vital for correct data manipulation, +including automatic transliteration between character sets when necessary. + +!!! important + + Because data also flow between server and client application, it's vital that client + will send data encoded only in character set(s) that server expects. While it's + possible to leave this responsibility completely on client application, it's better + when client and server settle on single character set they would use for communication, + especially when database operates with multiple character sets, or uses character set + that is not `native` for client application. + + Character set for communication is specified using `~.DatabaseConfig.charset` + configuration option, or parameter in `.connect()` or `~firebird.driver.core.create_database()` call. + + When `connection charset` is defined, all textual data returned from server are encoded + in this charset, and client application must ensure that all textual data sent to server + are encoded only in this charset as well. + +Firebird-driver helps with client side of this character set bargain by automatically +converting Python `str` values into `bytes` encoded in connection character set, +and vice versa. However, developers are still responsible that `bytes` strings +passed to server are in correct encoding (because firebird-driver makes no assumption +about encoding of `bytes` strings, so it can't recode them to connection charset). + +!!! important + + In case that `connection charset` is NOT defined at all, or `NONE` charset is specified, + firebird-driver uses `locale.getpreferredencoding` to determine encoding for conversions + from/to `unicode`. + +!!! important + + There is one exception to automatic conversion: when character set OCTETS is defined + for data column. Values assigned to OCTETS columns are always passed `as is`, because + they're basically binary streams. This has specific implications. Python 3 native + strings are `unicode`, and you would probably want to use `bytes` type instead. However, + firebird-driver in this case doesn't check the value type at all, so you'll not be + warned if you'll make a mistake and pass `str` to OCTETS column (unless you'll pass + more bytes than column may hold, or you intend to store unicode that way). + +Conversion is fully automatic in both directions for all textual data, i.e. including +for string values returned by Firebird Service and `info` calls etc. When `connection +charset` is not specified, firebird-driver uses `locale.getpreferredencoding` to +determine encoding for conversions from/to `unicode`. + +!!! tip + + Except for legacy databases that doesn't have `character set` defined, **always** + define character set for your databases and specify `connection charset`. It will + make your life much easier. + + + + +## Working with TIME/TIMESTAMP WITH TIMEZONE + +Firebird 4 introduced support for TIME and TIMESTAMP WITH TIMEZONE. The driver supports these +types with timezone-aware `datetime.datetime` and `datetime.time` objects. However, this +support has some specific limitations: + +1. The driver uses `python-dateutil` package to handle timezone information. Due to specific + requirements it's not possible to use standard `zoneinfo` package available in Python since + version 3.9, neither any other `datetime.tzinfo` implementation. +2. All timezone-aware `datetime.datetime` and `datetime.time` objects passed to the driver + must use `datetime.tzinfo` created with `.get_timezone()` utility function. + +**Examples:** + +```python +from firebird.driver import get_timezone + +ts_region = datetime.datetime(2020, 12, 31, 23, 55, 35, 123400, get_timezone('Europe/Prague')) +ts_offset = datetime.datetime(2020, 12, 31, 23, 55, 35, 123400, get_timezone('+02:00')) + +``` + +## Working with BLOBs + +Firebird-driver uses two types of BLOB values: + +* **Materialized** BLOB values are Python `str` or `bytes` values. This is the **default** type. +* **Streamed** BLOB values are `file-like` objects. + +Materialized BLOBs are easy to work with, but are not suitable for: + +* **deferred loading** of BLOBs. They're called `materialized` because they're always + fetched from server as part of row fetch. Fetching BLOB value means separate API calls + (and network roundtrips), which may slow down you application considerably. +* **large values**, as they are always stored in memory in full size. + +These drawbacks are addressed by `stream` BLOBs. Using BLOBs in `stream` mode is easy: + +* For **input** values, simply use [parameterized statement](executing-sql-statements.md#parameterized-statements) + and pass any `file-like` object in place of BLOB parameter. The `file-like` object must + implement only the `~file.read` method, as no other method is used. +* For **output** values, add column name(s) that should be returned as `file-like` + objects to `.Cursor.stream_blobs` list attribute. Firebird-driver then returns + `.BlobReader` instance instead string in place of returned BLOB value for these column(s). + +!!! important + + The firebird-driver provides `.Cursor.stream_blob_threshold` attribute that controls + the maximum size of materialized blobs (as memory exhaustion safeguard). When particular + blob value exceeds this threshold, an instance of `.BlobReader` is returned instead + string/bytes value. + + Zero threshold value effectively forces all blobs to be returned as stream blobs. + Negative value means no size limit for materialized blobs (use at your own risk). + Please note that positive threshold value means that your application has to be + prepared to handle BLOBs in both incarnations. + + The default threshold is 64K and could be changed using `.DriverConfig.stream_blob_threshold` + configuration option. + + Blob size threshold has effect only on materialized blob columns, i.e. columns not + explicitly requested to be returned as streamed ones using `.Cursor.stream_blobs` + attribute, that are **always** returned as stream blobs. + +The `.BlobReader` instance is bound to `.Cursor` instance, and it's automatically closed +with cursor. However, it's good practice to use `with` statement or call `.BlobReader.close()` +once you're finished reading to release system resources associated with BLOB value. + +!!! important + + When working with BLOB values, always have memory efficiency in mind, especially when + you're processing huge quantity of rows with BLOB values at once. Materialized BLOB + values may exhaust your memory quickly, but using stream BLOBs may have inpact on + performance too, as new `.BlobReader` instance is created for each value fetched. + +**Example program:** + +```python +from firebird.driver import connect + +with connect('employee', user='SYSDBA', password='masterkey') as con: + cur = con.cursor() + print("Materialized retrieval (as str):") + cur.execute('select proj_id, proj_desc from project') + proj_id, proj_desc = cur.fetchone() + print(f"{proj_id=}, {proj_desc=}") + + print("\nStreaming retrieval (via BlobReader):") + cur.stream_blobs.append('PROJ_DESC') + cur.execute('select proj_id, proj_desc from project') + proj_id, proj_desc = cur.fetchone() + with proj_desc: + print(f"{proj_id=}, {proj_desc=}") + print(proj_desc.read()) + +``` + +Output: + +```text +Materialized retrieval (as str): +proj_id='VBASE', proj_desc='Design a video data base management system for\ncontrolling on-demand video distribution.\n' + +Streaming retrieval (via BlobReader): +proj_id='VBASE', proj_desc=BlobReader[size=89] +Design a video data base management system for +controlling on-demand video distribution. + +``` + +## Firebird ARRAY type + +Firebird-driver supports Firebird ARRAY data type. ARRAY values are represented as +Python lists. On input, the Python sequence (list or tuple) must be nested appropriately +if the array field is multi-dimensional, and the incoming sequence must not fall short +of its maximum possible length (it will not be “padded” implicitly–see below). On output, +the lists will be nested if the database array has multiple dimensions. + +!!! note + + Database arrays have no place in a purely relational data model, which requires that + data values be atomized (that is, every value stored in the database must be reduced + to elementary, non-decomposable parts). The Firebird implementation of database arrays, + like that of most relational database engines that support this data type, is fraught + with limitations. + + Database arrays are of fixed size, with a predeclared number of dimensions (max. 16) + and number of elements per dimension. Individual array elements cannot be set to + NULL / None, so the mapping between Python lists (which have dynamic length and are + therefore not normally “padded” with dummy values) and non-trivial database arrays is + clumsy. + + Stored procedures cannot have array parameters. + + Finally, many interface libraries, GUIs, and even the isql command line utility do not + support database arrays. + + In general, it is preferable to avoid using database arrays unless you have a compelling + reason. + +**Example:** + +```python +>>> from firebird.driver import connect +>>> con = connect('employee',user='sysdba', password='masterkey') +>>> cur = con.cursor() +>>> cur.execute("select LANGUAGE_REQ from job where job_code='Eng' and job_grade=3 and job_country='Japan'") +>>> cur.fetchone() +(['Japanese\n', 'Mandarin\n', 'English\n', '\n', '\n'],) + +``` + +**Example program:** + +```python +from firebird.driver import connect + +arrayIn = [ + [1, 2, 3, 4], + [5, 6, 7, 8], + [9,10,11,12] + ] + +with connect('/temp/test.db', user='sysdba', password='pass') as con: + con.execute_immediate("recreate table array_table (a int[3,4])") + con.commit() + + cur = con.cursor() + + print(f"{arrayIn=}") + cur.execute("insert into array_table values (?)", (arrayIn,)) + con.commit() + + cur.execute("select a from array_table") + arrayOut = cur.fetchone()[0] + print(f"{arrayOut=}) + +``` + +Output: + +```text +arrayIn=[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] +arrayOut=[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] + +``` diff --git a/docs/docs/usage-guide/database-events.md b/docs/docs/usage-guide/database-events.md new file mode 100644 index 0000000..d518acd --- /dev/null +++ b/docs/docs/usage-guide/database-events.md @@ -0,0 +1,282 @@ +# Database Events + +## What they are +The Firebird engine features a distributed, inter-process communication mechanism based on +messages called `database events`. A database event is a message passed from a trigger or +stored procedure to an application to announce the occurrence of a specified condition or +action, usually a database change such as an insertion, modification, or deletion of a record. +The Firebird event mechanism enables applications to respond to actions and database changes +made by other, concurrently running applications without the need for those applications to +communicate directly with one another, and without incurring the expense of CPU time +required for periodic polling to determine if an event has occurred. + +## Why use them +Anything that can be accomplished with database events can also be implemented using other +techniques, so why bother with events? Since you’ve chosen to write database-centric programs +in Python rather than assembly language, you probably already know the answer to this question, +but let’s illustrate. + +A typical application for database events is the handling of administrative messages. +Suppose you have an administrative message database with a `message's` table, into which +various applications insert timestamped status reports. It may be desirable to react to +these messages in diverse ways, depending on the status they indicate: to ignore them, to +initiate the update of dependent databases upon their arrival, to forward them by e-mail +to a remote administrator, or even to set off an alarm so that on-site administrators will +know a problem has occurred. + +It is undesirable to tightly couple the program whose status is being reported +(the `message producer`) to the program that handles the status reports (the `message handler`). +There are obvious losses of flexibility in doing so. For example, the message producer may +run on a separate machine from the administrative message database and may lack access rights +to the downstream reporting facilities (e.g., network access to the SMTP server, in the case +of forwarded e-mail notifications). Additionally, the actions required to handle status +reports may themselves be time-consuming and error-prone, as in accessing a remote network +to transmit e-mail. + +In the absence of database event support, the message handler would probably be implemented +via `polling`. Polling is simply the repetition of a check for a condition at a specified +interval. In this case, the message handler would check in an infinite loop to see whether +the most recent record in the `messages` table was more recent than the last message it had +handled. If so, it would handle the fresh message(s); if not, it would go to sleep for +a specified interval, then loop. + +The `polling-based` implementation of the message handler is fundamentally flawed. Polling +is a form of [busy-wait](http://www.catb.org/jargon/html/B/busy-wait.html); the check for new messages is performed at the specified interval, +regardless of the actual activity level of the message producers. If the polling interval +is lengthy, messages might not be handled within a reasonable time period after their arrival; +if the polling interval is brief, the message handler program (and there may be many such +programs) will waste a large amount of CPU time on unnecessary checks. + +The database server is necessarily aware of the exact moment when a new message arrives. +Why not let the message handler program request that the database server send it a notification +when a new message arrives? The message handler can then efficiently sleep until the moment +its services are needed. Under this `event-based` scheme, the message handler becomes +aware of new messages at the instant they arrive, yet it does not waste CPU time checking +in vain for new messages when there are none available. + +## How events are exposed + +1. Server Process ("An event just occurred!") + + To notify any interested listeners that a specific event has + occurred, issue the `POST_EVENT` statement from Stored Procedure + or Trigger. The `POST_EVENT` statement has one parameter: the name + of the event to post. In the preceding example of the administrative + message database, `POST_EVENT` might be used from an `after insert` + trigger on the `messages` table, like this: + + ```sql + create trigger trig_messages_handle_insert + for messages + after insert + as + begin + POST_EVENT 'new_message'; + end + + ``` + + !!! note + The physical notification of the client process does not + + occur until the transaction in which the `POST_EVENT` took place is + actually committed. Therefore, multiple events may *conceptually* + occur before the client process is *physically* informed of even one + occurrence. Furthermore, the database engine makes no guarantee that + clients will be informed of events in the same groupings in which they + conceptually occurred. If, within a single transaction, an event named + `event_a` is posted once and an event named `event_b` is posted once, + the client may receive those posts in separate "batches", despite the + fact that they occurred in the same conceptual unit (a single + transaction). This also applies to multiple occurrences of *the same* + event within a single conceptual unit: the physical notifications may + arrive at the client separately. + +1. Client Process ("Send me a message when an event occurs.") + + !!! note + If you don't care about the gory details of event notification, + + skip to the section that describes FDB's Python-level event handling + API. + + The Firebird C client library offers two forms of event notification. + The first form is *synchronous* notification, by way of the function + `isc_wait_for_event()`. This form is admirably simple for a C programmer + to use, but is inappropriate as a basis for FDB's event support, + chiefly because it's not sophisticated enough to serve as the basis for + a comfortable Python-level API. The other form of event notification + offered by the database client library is *asynchronous*, by way of the + functions `isc_que_events()` (note that the name of that function + is misspelled), `isc_cancel_events()`, and others. The details are + as nasty as they are numerous, but the essence of using asynchronous + notification from C is as follows: + + 1. Call `isc_event_block()` to create a formatted binary buffer that will tell + the server which events the client wants to listen for. + 1. Call `isc_que_events()` (passing the buffer created in the previous step) to + inform the server that the client is ready to receive event notifications, and provide + a callback that will be asynchronously invoked when one or more of the registered events occurs. + 1. [The thread that called `isc_que_events()` to initiate event listening must + now do something else.] + 1. When the callback is invoked (the database client library starts a thread dedicated + to this purpose), it can use the `isc_event_counts()` function to determine + how many times each of the registered events has occurred since the last call to + `isc_event_counts()` (if any). + 1. [The callback thread should now "do its thing", which may include communicating with + the thread that called `isc_que_events()`.] + 1. When the callback thread is finished handling an event notification, it must call + `isc_que_events()` again in order to receive future notifications. Future + notifications will invoke the callback again, effectively "looping" the callback + thread back to Step 4. + +## API for Python developers + +The Firebird-driver database event API is comprised of the following: the method +`.Connection.event_collector()` and the class `.EventCollector`. + +Use the `.Connection.event_collector()` method (takes a sequence of string event +names as parameter) to create `.EventCollector` instance, that collects database event +notifications sent from the server for given database. + +!!! important + + To start listening for events it's necessary to call `.EventCollector.begin()` + method or use EventCollector's context manager interface. + +Immediately when `~.EventCollector.begin()` method is called, EventCollector starts +to accumulate notifications of any event that occur within the collector’s internal queue +until the collector is closed either explicitly (via the `~.EventCollector.close()` +method) or implicitly (via garbage collection). + +Notifications about events are aquired through call to `~.EventCollector.wait()` method, +that blocks the calling thread until at least one of the events occurs, or the specified +`timeout` (if any) expires, and returns `None` if the wait timed out, or a dictionary that +maps `event_name -> event_occurrence_count`. + +!!! important + + `.EventCollector` can act as context manager that ensures execution of + `~.EventCollector.begin()` and `~.EventCollector.close()` methods. + It's strongly advised to use the `.EventCollector` with the `with` statement. + +**Example:** + +```python +with connection.event_collector(['event_a', 'event_b']) as collector: + events = collector.wait() + process_events(events) + +``` + +If you want to drop notifications accumulated so far by conduit, call +`.EventCollector.flush()` method. + +**Example program:** + +```python +from firebird.driver import create_database, transaction +import threading +import time + +# Prepare database +con = create_database('event-test', user='SYSDBA', password='masterkey') +with transaction(con): + con.execute_immediate("CREATE TABLE T (PK Integer, C1 Integer)") + con.execute_immediate("""CREATE TRIGGER EVENTS_AU FOR T ACTIVE + BEFORE UPDATE POSITION 0 + AS + BEGIN + if (old.C1 <> new.C1) then + post_event 'c1_updated' ; + END""") + con.execute_immediate("""CREATE TRIGGER EVENTS_AI FOR T ACTIVE + AFTER INSERT POSITION 0 + AS + BEGIN + if (new.c1 = 1) then + post_event 'insert_1' ; + else if (new.c1 = 2) then + post_event 'insert_2' ; + else if (new.c1 = 3) then + post_event 'insert_3' ; + else + post_event 'insert_other' ; + END""") +cur = con.cursor() + +# Utility function +def send_events(command_list): + with transaction(con): + for cmd in command_list: + cur.execute(cmd) + +print("One event") +# ========= +timed_event = threading.Timer(3.0,send_events,args=[["insert into T (PK,C1) values (1,1)",]]) +with con.event_collector(['insert_1']) as events: + timed_event.start() + e = events.wait() +print(e) + +print("Multiple events") +# =============== +cmds = ["insert into T (PK,C1) values (1,1)", + "insert into T (PK,C1) values (1,2)", + "insert into T (PK,C1) values (1,3)", + "insert into T (PK,C1) values (1,1)", + "insert into T (PK,C1) values (1,2)",] +timed_event = threading.Timer(3.0,send_events,args=[cmds]) +with con.event_collector(['insert_1','insert_3']) as events: + timed_event.start() + e = events.wait() +print(e) + +print("20 events") +# ========= +cmds = ["insert into T (PK,C1) values (1,1)", + "insert into T (PK,C1) values (1,2)", + "insert into T (PK,C1) values (1,3)", + "insert into T (PK,C1) values (1,1)", + "insert into T (PK,C1) values (1,2)",] +timed_event = threading.Timer(1.0,send_events,args=[cmds]) +with con.event_collector(['insert_1','A','B','C','D', + 'E','F','G','H','I','J','K','L','M', + 'N','O','P','Q','R','insert_3']) as events: + timed_event.start() + time.sleep(3) + e = events.wait() +print(e) + +print("Flush events") +# ============ +timed_event = threading.Timer(3.0,send_events,args=[["insert into T (PK,C1) values (1,1)",]]) +with con.event_collector(['insert_1']) as events: + send_events(["insert into T (PK,C1) values (1,1)", + "insert into T (PK,C1) values (1,1)"]) + time.sleep(2) + events.flush() + timed_event.start() + e = events.wait() +print(e) + +# Finalize +con.drop_database() +con.close() + +``` + +Output: + +```text +One event +{'insert_1': 1} +Multiple events +{'insert_3': 1, 'insert_1': 2} +20 events +{'A': 0, 'C': 0, 'B': 0, 'E': 0, 'D': 0, 'G': 0, 'insert_1': 2, 'I': 0, 'H': 0, 'K': 0, 'J': 0, 'M': 0, + 'L': 0, 'O': 0, 'N': 0, 'Q': 0, 'P': 0, 'R': 0, 'insert_3': 1, 'F': 0} +Flush events +{'insert_1': 1} + +``` diff --git a/docs/docs/usage-guide/databases.md b/docs/docs/usage-guide/databases.md new file mode 100644 index 0000000..91d2ef3 --- /dev/null +++ b/docs/docs/usage-guide/databases.md @@ -0,0 +1,496 @@ +# Databases + +Access to the database is made available through `.Connection` objects. Firebird-driver +provides two constructors for these: + +* `.connect` - Returns `.Connection` to database that already exists. +* `~firebird.driver.core.create_database` - Returns `.Connection` to newly created database. + + + +## Using connect() + +This constructor has one positional and several keyword parameters. + +The value of `database` positional parameter must be one of: + +* name of registered database configuration +* database name / alias + +!!! important + This value **cannot** be DSN / fully qualified Firebird connection string! + +Keyword parameters are intended to override selected configuration options, or to specify +options that are not configurable. + +!!! note + + If `database` value is not recognized as name of registered database configuration, + the driver uses `~.DriverConfig.db_defaults` and `~.DriverConfig.server_defaults` + configuration objects. + +A simple database connection is typically established with code such as this: + +```python +from firebird.driver import connect + +# Attach to 'employee' database/alias using embedded server connection +con = connect('employee', user='sysdba', password='masterkey') + +# Attach to 'employee' database/alias using local server connection +from firebird.driver import driver_config +driver_config.server_defaults.host.value = 'localhost' +con = connect('employee', user='sysdba', password='masterkey') + +# Set 'user' and 'password' via configuration +driver_config.server_defaults.user.value = 'SYSDBA' +driver_config.server_defaults.password.value = 'masterkey' +con = connect('employee') + +``` + +However, it's recommended to use specific configuration for servers and databases. +It's possible to register servers and databases directly in code like this: + +```python +from firebird.driver import connect, driver_config + +# Register Firebird server +srv_cfg = """[local] +host = localhost +user = SYSDBA +password = masterkey +""" +driver_config.register_server('local', srv_cfg) + +# Register database +db_cfg = """[employee] +server = local +database = employee.fdb +protocol = inet +charset = utf8 +""" +driver_config.register_database('employee', db_cfg) + +# Attach to 'employee' database +con = connect('employee') + +``` + +But more convenient approach is using single configuration file: + +```text +# file: myapp.cfg + +[firebird.driver] +servers = local +databases = employee + +[local] +host = localhost +user = SYSDBA +password = masterkey + +[employee] +server = local +database = employee.fdb +protocol = inet +charset = utf8 + +``` + +```python +from firebird.driver import connect, driver_config + +driver_config.read('myapp.cfg') + +# Attach to 'employee' database +con = connect('employee') + +``` + +!!! info + `.connect()` for details. + + +## Using create_database() + +This constructor returns connection to newly created database. It works in the same way +as `.connect()`, but utilizes additional database configuration options. + +It's possible to specify these options in code like this: + +```python +from firebird.driver import connect, driver_config + +# Register Firebird server +srv_cfg = """[local] +host = localhost +user = SYSDBA +password = masterkey +""" +driver_config.register_server('local', srv_cfg) + +# Register database +db_cfg = """[mydb] +server = local +database = mydb.fdb +protocol = inet +charset = utf8 +# create options +page_size = 16384 +db_charset = utf8 +sweep_interval = 80000 +reserve_space = no +""" +driver_config.register_database('mydb', db_cfg) + +# create 'mydb' database +con = create_database('mydb') + +``` + +But more convenient approach is using single configuration file: + +```text +# file: myapp.cfg + +[firebird.driver] +servers = local +databases = mydb + +[local] +host = localhost +user = SYSDBA +password = masterkey + +[mydb] +server = local +database = mydb.fdb +protocol = inet +charset = utf8 +# create options +page_size = 16384 +db_charset = utf8 +sweep_interval = 80000 +reserve_space = no + +``` + +```python +from firebird.driver import create_database, driver_config + +driver_config.read('myapp.cfg') + +# create 'mydb' database +con = create_database('mydb') + +``` + +!!! info + `~firebird.driver.core.create_database()` for details. + + +## Deleting databases + +The Firebird engine also supports dropping (deleting) databases dynamically, +but dropping is a more complicated operation than creating, for several reasons: +an existing database may be in use by users other than the one who requests +the deletion, it may have supporting objects such as temporary sort files, and +it may even have dependent shadow databases. Although the database engine +recognizes a `DROP DATABASE` SQL statement, support for that statement is limited +to the `isql` command-line administration utility. However, the engine supports +the deletion of databases via an API call, which `firebird-driver` exposes as +`~.Connection.drop_database` method in `.Connection` class. So, to drop a database +you need to connect to it first. + +**Example:** + +```python +from firebird.driver import connect, driver_config + +driver_config.read('myapp.cfg') + +# Attach to 'myapp' database +con = connect('myapp') +con.drop_database() + +``` + +!!! info + `.Connection.drop_database()` for details. + + +## Connection object + +`.Connection` object represents a direct link to database, and works as +gateway for next operations with it: + +* [Executing SQL Statements](executing-sql-statements.md#executing-sql-statements): methods `~.Connection.execute_immediate()` and `~.Connection.cursor()`. +* [Dropping database](databases.md#deleting-databases): method `~.Connection.drop_database()`. +* [Transanction management](transanction-management.md#transanction-management): methods `~.Connection.begin()`, `~.Connection.commit()`, + `~.Connection.rollback()`, `~.Connection.savepoint()`, `~.Connection.transaction_manager()`, + `~.Connection.is_active()`, and attributes `~.Connection.main_transaction`, + `~.Connection.query_transaction`, `~.Connection.transactions` and `~.Connection.default_tpb`. +* Work with [Database Events](database-events.md#database-events): method `~.Connection.event_collector`. +* [Getting information about connection](databases.md#getting-information-about-connection): methods `~.Connection.is_closed()` and + `~.Connection.ping()` and attributes `~.Connection.dsn`, `~.Connection.charset` + and `~.Connection.sql_dialect`. +* [Getting information about database](databases.md#getting-information-about-database): attribute `~.Connection.info`. +* [Closing the connection](databases.md#closing-the-connection): method `~.Connection.close()` + + +## Closing the connection + +There are many local and server resources used by firebird-driver that must be properly +managed, and disposed when they are no longer necessary. All objects that require proper +finalization provide `close()` method that must be called when object is no longer needed. +The `.Connection` (and `.Server`) objects are the most important ones, as other most frequently +used objects like cursors, prepared statements and transactions are typically associated with +connections. + +You may call the `close()` method directly, or use the with statement +and context manager support provided by all these objects. + +**Example:** + +```python +from firebird.driver import connect, driver_config + +driver_config.read('myapp.cfg') + +with connect('employee') as con: + cur = con.cursor() + cur.execute('select 1 from rdb$database') + print(cur.fetchone()[0]) + + +``` + +!!! note + + Objects that require proper finalization are: `.Connection`, `.TransactionManager` + and `.DistributedTransactionManager`, `.Statement`, `.BlobReader`, `.Cursor` and `.Server`. + + Although only `.Connection` and `.Server` objects must be closed directly because + all other objects are associated with them and thus closed when connection is + closed, it's **recommended** to directly close any resource object obtained by + your code when it's no longer needed (either directly by calling `close()` or using + `with` statement). + +!!! important + + All managed objects have `~object.__del__` method, which ensures that the object in + the active state is properly closed before it is destroyed by the Python memory manager. + However, **the close operation may fail** as the state of your application could be arbitrary + and the sequence in which objects are disposed by memory manager is not deterministic. + + The `~object.__del__` methods should be thus considered as safe guard of last resort + that your code should not rely upon. To indicate that your code is not managing + resources properly, the `ResourceWarning` is raises when active object is disposed + by memory manager. + + !!! note + + Such warnings may not reach your attention if warnings are disabled or filtered + on your system. You should always develop and test your applications with enabled + delivery of resource warnings. + +!!! info + `.Connection.close()` for details. + + +## Getting information about connection + +Only (most useful) part of information associated with `.Connection` object is directly +available: + +* It's possible to check whether Connection object is closed or not with + `~.Connection.is_closed()` method. +* It's possible to check whether connection to the Firebird server is not broken with + `~.Connection.ping()` method. +* The DSN (fully qualified Firebird database connection string) is surfaced as `~.Connection.dsn` + read-only property. +* The character set used by Connection is surfaced as `~.Connection.charset` read-only property. +* The SQL dialect used by Connection is surfaced as `~.Connection.sql_dialect` read-only property. + +!!! tip + + Additional connection-specific information is currently held as `bytes` in protected + `Connection._dpb` attribute that could be processed using `~firebird.driver.core.DPB` object. + + +## Getting information about database + +!!! important + + Because the scope and type of database information depends on the version of the Firebird + server and database ODS, this information is made available through a separate class + `.DatabaseInfoProvider`. The `.Connection.info` property provides access to + instance of `.DatabaseInfoProvider` or it's **ancestor** class according to ODS of attached + database and Firebird version. + +Although you may query the information directly from server using +`~firebird.driver.core.DatabaseInfoProvider3.get_info()` method (that wraps the Firebird +`.iAttachment.getInfo()` API call), the `.DatabaseInfoProvider` object +provides more convenient methods and properties for obtaining specific information directly. + +!!! note + + Some information provided by `.DatabaseInfoProvider` properties + (like `~.DatabaseInfoProvider3.cache_hit_ratio`) could not be obtained via + `get_info()` method. + +**Example:** + +```python +from firebird.driver import connect + +with connect('employee', user='SYSDBA', password='masterkey') as con: + print(f"Database character set: {con.info.charset}") + print(f"Page size (in bytes): {con.info.page_size}") + print(f"Attachment ID: {con.info.id}") + print(f"SQL dialect used by connected database: {con.info.sql_dialect}") + print(f"Database name (filename or alias): {con.info.name}") + print(f"Database site name: {con.info.site}") + print(f"Implementation (old format): {con.info.implementation!s}") + print(f"Database Provider: {con.info.provider!s}") + print(f"Database Class: {con.info.db_class!s}") + print(f"Date when database was created: {con.info.creation_date}") + print(f"Size of page cache used by connection: {con.info.page_cache_size}") + print(f"Number of pages allocated for database: {con.info.pages_allocated}") + print(f"Number of database pages in active use: {con.info.pages_used}") + print(f"Number of free allocated pages in database: {con.info.pages_free}") + print(f"Sweep interval: {con.info.sweep_interval}") + print(f"Data page space usage (USE_FULL or RESERVE): {con.info.space_reservation!s}") + print(f"Database write mode (SYNC or ASYNC): {con.info.write_mode!s}") + print(f"Database access mode (READ_ONLY or READ_WRITE): {con.info.access_mode!s}") + print(f"Current I/O statistics - Reads from disk to page cache: {con.info.reads}") + print(f"Current I/O statistics - Fetches from page cache: {con.info.fetches}") + print(f"Cache hit ratio = 1 - (reads / fetches): {con.info.cache_hit_ratio}") + print(f"Current I/O statistics - Writes from page cache to disk: {con.info.writes}") + print(f"Current I/O statistics - Writes to page in cache: {con.info.marks}") + print(f"Total amount of memory curretly used by database engine: {con.info.current_memory}") + print(f"Max. total amount of memory so far used by database engine: {con.info.max_memory}") + print(f"ID of Oldest Interesting Transaction: {con.info.oit}") + print(f"ID of Oldest Active Transaction: {con.info.oat}") + print(f"ID of Oldest Snapshot Transaction: {con.info.ost}") + print(f"ID for next transaction: {con.info.next_transaction}") + +``` + +**Sample output**: + +```text +Database character set: NONE +Page size (in bytes): 8192 +Attachment ID: 378 +SQL dialect used by connected database: 3 +Database name (filename or alias): /opt/firebird/examples/empbuild/employee.fdb +Database site name: NewAmarisk +Implementation (old format): Implementation.RDB_VMS +Database Provider: DbProvider.FIREBIRD +Database Class: DbClass.SERVER_ACCESS +Date when database was created: 2020-05-13 10:13:57.005010 +Size of page cache used by connection: 2048 +Number of pages allocated for database: 346 +Number of database pages in active use: 311 +Number of free allocated pages in database: 35 +Sweep interval: 20000 +Data page space usage (USE_FULL or RESERVE): DbSpaceReservation.RESERVE +Database write mode (SYNC or ASYNC): DbWriteMode.SYNC +Database access mode (READ_ONLY or READ_WRITE): DbAccessMode.READ_WRITE +Current I/O statistics - Reads from disk to page cache: 87 +Current I/O statistics - Fetches from page cache: 1525 +Cache hit ratio = 1 - (reads / fetches): 0.9429508196721311 +Current I/O statistics - Writes from page cache to disk: 2 +Current I/O statistics - Writes to page in cache: 5 +Total amount of memory curretly used by database engine: 21925248 +Max. total amount of memory so far used by database engine: 22033760 +ID of Oldest Interesting Transaction: 307 +ID of Oldest Active Transaction: 308 +ID of Oldest Snapshot Transaction: 308 +ID for next transaction: 308 + +``` + +!!! info + `.DatabaseInfoProvider` for details. + +#### Getting information about Firebird version + +Because functionality and some features depends on actual Firebird version, it could be +important for driver users to check it. This (otherwise) simple task could be confusing +for new Firebird users, because Firebird uses two different version lineages. This abomination +was introduced to Firebird thanks to its InterBase legacy (Firebird 1.0 is a fork of InterBase +6.0), as applications designed to work with InterBase can often work with Firebird without +problems (and vice versa). + +`.DatabaseInfoProvider` provides these version strings as two properties: + +* `~.DatabaseInfoProvider.server_version` - Legacy InterBase-friendly version string. +* `~.DatabaseInfoProvider.firebird_version` - Firebird’s own version string. + +However, this version string contains more information than version number. For example for +Linux Firebird 4.0.0 it’s ‘LI-T4.0.0.1963 Firebird 4.0 Beta 2’. So `.DatabaseInfoProvider` +provides two more properties for your convenience: + +* `~.DatabaseInfoProvider.version` - Only Firebird version number. It’s a string with + format: major.minor.subrelease.build +* `~.DatabaseInfoProvider.engine_version` - Engine (major.minor) version as (float) number. + + +**Example:** + +```python +from firebird.driver import connect + +with connect('employee', user='SYSDBA', password='masterkey') as con: + print(f"server_version: '{con.info.server_version}'") + print(f"firebird_version: '{con.info.firebird_version}'") + print(f"version: '{con.info.version}'") + print(f"engine_version: {con.info.engine_version}") + +``` + +**Sample output**: + +```text +server_version: 'LI-T6.3.0.1963 Firebird 4.0 Beta 2' +firebird_version: 'LI-T4.0.0.1963 Firebird 4.0 Beta 2' +version: '4.0.0.1963' +engine_version: 4.0 + +``` +#### Database On-Disk Structure + +Particular Firebird features may also depend on specific support in database +(for example number and structure of monitoring tables). These required structures are +present automatically when database is created by particular engine verison that needs +them, but Firebird engine may work with databases created by older versions and thus with +older structure, so it could be necessary to consult also On-Disk Structure (ODS for short) +version. `.DatabaseInfoProvider` provides this number as `~.DatabaseInfoProvider.ods` (float) +property. + +**Example:** + +```python +from firebird.driver import connect + +with connect('employee', user='SYSDBA', password='masterkey') as con: + print(f"ods: {con.info.ods}") + print(f"ods_version: {con.info.ods_version}") + print(f"ods_minor_version: {con.info.ods_minor_version}") + +``` + +**Sample output**: + +```text +ods: 13.0 +ods_version: 13 +ods_minor_version: 0 + + + +``` diff --git a/docs/docs/usage-guide/driver-hooks.md b/docs/docs/usage-guide/driver-hooks.md new file mode 100644 index 0000000..b434915 --- /dev/null +++ b/docs/docs/usage-guide/driver-hooks.md @@ -0,0 +1,70 @@ + + + + +# Driver hooks + +The firebird-driver uses [hook manager](https://firebird-base.readthedocs.io/en/latest/hooks/) from [firebird-base](https://firebird-base.rtfd.io) package +to provide internal notification mechanism that allows installation of custom hooks into +certain driver tasks. + +Driver hooks are divided into several types exposed as enums in `firebird.driver.hooks` module. + +## APIHook + +`.APIHook.LOADED` - This hook is invoked once when instance of `.FirebirdAPI` is created. +It could be used for additional initialization tasks that require Firebird API, or to manipulate +the FirebirdAPI instance itself before its use. + +Hook routine must have signature: `hook_func(api: FirebirdAPI) -> None`. Any value returned +by hook is ignored. + +## ConnectionHook + +* `.ConnectionHook.ATTACH_REQUEST` + + This hook is invoked after all parameters are preprocessed and before `.Connection` is created. + + Hook routine must have signature: `hook_func(dsn: str, dpb: bytes) -> Optional[Connection]` + where `dpb` is Database Parameter Buffer that would be used to create the attachment to the + database defined by `dsn`. It may return `.Connection` (or subclass) instance or `None`. + + First instance returned by any hook of this type will become the return value of caller function + and other hooks of the same type are not invoked. + +* `.ConnectionHook.ATTACHED` + + This hook is invoked just before `.Connection` (or subclass) instance is returned to the client + application. + + Hook routine must have signature: `hook_func(con: Connection) -> None`. + +* `.ConnectionHook.DETACH_REQUEST` + + This hook is invoked before connection is closed. + + Hook must have signature: `hook_func(con: Connection) -> None`. + + If any hook function returns True, connection is not closed. + +* `.ConnectionHook.CLOSED` + + This hook is invoked after connection is closed. + + Hook routine must have signature: `hook_func(con: Connection) -> None`. + +* `.ConnectionHook.DROPPED` + + This hook is invoked after database is dropped (and connection is closed). + + Hook routine must have signature: `hook_func(con: Connection) -> None`. + +## ServerHook + +* `.ServerHook.ATTACHED` + + This hook is invoked before `.Server` instance is returned. + + Hook routine must have signature: `hook_func(srv: Server) -> None`. + + diff --git a/docs/docs/usage-guide/driver-structure.md b/docs/docs/usage-guide/driver-structure.md new file mode 100644 index 0000000..3e17d65 --- /dev/null +++ b/docs/docs/usage-guide/driver-structure.md @@ -0,0 +1,53 @@ +# Driver structure + +Source code is currently divided into next submodules: + +* `types` - Data types used by driver. +* `interfaces` - Interface wrappers for Firebird new API +* `core` - Main driver source code. +* `fbapi` - Python `ctypes` interface to Firebird client library. +* `config` - Driver configuration. +* `hooks` - Drivers hooks. + +All important data, functions, classes and constants are available directly in `firebird.driver` +name space. In normal circumstances is not necessary to import sub-modules directly. However, +you may need them to access some not so frequently needed driver functionality like driver +hooks, or to implement your own callback interfaces. + +!!! important + + `firebird-driver` is designed to support all Firebird versions starting from version 3.0. + Because each Firebird major version adds new functionality, and Firebird OO API could + be extended even in maintenance releases, the driver isolates volatile functionality + into special class hierarchies. + + For example information about database (provided via `~.iAttachment_v3.get_info()` API + call) is isolated into separate `.DatabaseInfoProvider` class hierarchy. + The `.Connection.info` attribute then provides access to instance of appropriate class + - `.DatabaseInfoProvider` or its ancestor - for connected database. + The `.DatabaseInfoProvider` class **always** provides functionality of most recent + Firebird version supported by driver. + + This layout has several important consequences: + + 1. The `.DatabaseInfoProvider` class may change in major driver release if new Firebird + functionality is introduced. This normally represent no problems for client application + as backward compatibility is guaranteed. + 2. You should check the class hierarchy for "evolving" classes when you start using the + driver, and whenever you upgrade to new **major** driver version. If there are versioned + ancestor classes (they always have Firebird version number in their name) for canonical + (top level) ones, you should adjust your application to deal with situations when + instance of ancestor class is provided by driver instead top-level one, to prevent + run-time exceptions caused by access to functionality not provided by currently attached + Firebird server. + + !!! note + + The same apply for low-level API (`~firebird.driver.interfaces`) with difference + that they may change in minor driver releases (because API could be extended in + Firebird maintenance releases). + + !!! info + + `.DatabaseInfoProvider`, `.TransactionInfoProvider`, `.ServerInfoProvider`, + `.ServerDbServices`, `.ServerUserServices` and `.ServerTraceServices`. diff --git a/docs/docs/usage-guide/executing-sql-statements.md b/docs/docs/usage-guide/executing-sql-statements.md new file mode 100644 index 0000000..a00f303 --- /dev/null +++ b/docs/docs/usage-guide/executing-sql-statements.md @@ -0,0 +1,478 @@ +# Executing SQL Statements + +Firebird-driver implements two ways for execution of SQL commands against connected database: + +* `~.Connection.execute_immediate` - for execution of SQL commands that don't return any result. +* `.Cursor` objects that offer rich interface for execution of SQL commands and fetching their results. + + + +## Cursor object + +Because `.Cursor` objects always operate in context of single `.Connection` (and `.TransactionManager`), +`.Cursor` instances are not created directly, but by constructor method. Python DB API 2.0 assumes +that if database engine supports transactions, it supports only one transaction per connection, +hence it defines constructor method `~.Connection.cursor` (and other transaction-related methods) +as part of `.Connection` interface. However, Firebird supports multiple independent transactions +per connection. To conform to Python DB API, firebird-driver uses concept of internal +`~.Connection.main_transaction` and secondary `~.Connection.transactions`. Cursor constructor is +primarily defined by `.TransactionManager`, and Cursor constructor on `.Connection` is therefore +a shortcut for `main_transaction.cursor()`. + +`.Cursor` objects are used for next operations: + +* Execution of SQL Statemets: methods `~.Cursor.execute()`, `~.Cursor.executemany()`, `~.Cursor.open()` + and `~.Cursor.callproc()`. +* Creating `.Statement` objects for efficient repeated execution of SQL statements, and to obtain + additional information about SQL statements (like execution `~.Statement.plan`): method `~.Cursor.prepare()`. +* [Fetching results](executing-sql-statements.md#fetching-data-from-server): methods `~.Cursor.fetchone()`, `~.Cursor.fetchmany()`, + `~.Cursor.fetchall()`, `~.Cursor.fetch_next()`, `~.Cursor.fetch_prior()`, `~.Cursor.fetch_first()`, + `~.Cursor.fetch_last()`, `~.Cursor.fetch_absolute()` and `~.Cursor.fetch_relative()`. + + +## SQL Execution Basics + +There are five methods how to execute SQL commands: + +1. `.Connection.execute_immediate()` or `.TransactionManager.execute_immediate()` for SQL commands + that don't return any result, and are not executed frequently. This method also **doesn't** + support either [parameterized statements](executing-sql-statements.md#parameterized-statements) or + [prepared statements](executing-sql-statements.md#prepared-statements). + + !!! tip + + This method is efficient for `administrative` and [DDL](http://en.wikipedia.org/wiki/Data_Definition_Language) SQL commands, like `DROP`, `CREATE` + or `ALTER` commands, `SET STATISTICS` etc. + +2. `.Cursor.execute()` for SQL commands that return result sets, i.e. sequence of `rows` of the same + structure, and sequence has unknown number of `rows` (including zero). Each row of the sequence + can be read only once, and is returned in the order it is read from the server. + + !!! tip + + This method is preferred for all `SELECT` and other [DML](http://en.wikipedia.org/wiki/Data_Manipulation_Language) statements, or any statement that + is executed frequently, either `as is` or in `parameterized` form. + +3. `.Cursor.executemany()` for execution of single parameterized SQL command with various set + of parameters. + + !!! important + + Because `executemany()` is basically a simple loop that calls `execute()` with different + parameters, it's possible to execute any statement acceptable by `execute()`. However, + it's possible to access the result set **only** from last executed command, so this method + should not be used for SQL commands that return results. + +4. `.Cursor.open()` for SQL command that return result sets, i.e. sequence of `rows` of the same + structure, and sequence has unknown number of `rows` (including zero). Instead of just fetching + rows sequentially in a forward direction like `execute()`, this method allows flexible navigation + through an open cursor set both backwards and forwards. Rows next to, prior to and relative to + the current cursor row can be targeted. + + !!! info + [Scrollable cursors](executing-sql-statements.md#scrollable-cursors) for details. + +5. `.Cursor.callproc()` for execution of `Stored procedures` that always return exactly one set + of values. + + !!! note + + This method of SP invocation is equivalent to `"EXECUTE PROCEDURE ..."` SQL statement. + + +## Fetching data from server + +Result of SQL statement execution consists from sequence of zero to unknown number of `rows`, +where each `row` is a set of exactly the same number of values. `.Cursor` object offer number +of different methods for fetching these `rows`, that should satisfy all your specific needs: + +* `~.Cursor.fetchone()` - Returns the next row of a query result set, or `None` when no more data + is available. + + !!! tip + + Cursor supports the [iterator protocol](https://docs.python.org/3/library/stdtypes.html#iterator-types), yielding tuples of values + like `~.Cursor.fetchone()`. + +* `~.Cursor.fetchmany()` - Returns the next set of rows of a query result, returning a sequence + of sequences (e.g. a list of tuples). An empty sequence is returned when no more rows are available. + + The number of rows to fetch per call is specified by the parameter. If it is not given, the + cursor’s `~.Cursor.arraysize` determines the number of rows to be fetched. The method does try + to fetch as many rows as indicated by the size parameter. If this is not possible due to + the specified number of rows not being available, fewer rows may be returned. + + !!! note + + The default value of `~.Cursor.arraysize` is `1`, so without paremeter it's equivalent to + `~.Cursor.fetchone()`, but returns list of `rows`, instead actual `row` directly. + +* `~.Cursor.fetchall()` - Returns all (remaining) rows of a query result as list of tuples, + where each tuple is one row of returned values. + + !!! tip + + This method can potentially return huge amount of data, that may exhaust available memory. + If you need just `iteration` over potentially big result set, use loops with `~.Cursor.fetchone()` + or Cursor's built-in support for [iterator protocol](https://docs.python.org/3/library/stdtypes.html#iterator-types) instead this method. + +* Call to `~.Cursor.execute()` returns `self` (Cursor instance) that itself supports the + [iterator protocol](https://docs.python.org/3/library/stdtypes.html#iterator-types), yielding tuples of values like `~.Cursor.fetchone()`. + +!!! important + + Firebird-driver makes absolutely no guarantees about the `row` return value of the + `fetch*()` methods except that it is a sequence indexed by field position. Therefore, client + programmers should not rely on the return value being an instance of a particular class or type. + +**Examples:** + +```python +from firebird.driver import connect + +with connect('employee', user='SYSDBA', password='masterkey') as con: + cur = con.cursor() + SELECT = "select country, currency from country" + + # 1. Using built-in support for iteration protocol to iterate over the rows available + # from the cursor, unpacking the resulting sequences to yield their elements (country, currency): + cur.execute(SELECT) + for (country, currency) in cur: + print(f"{country} uses {currency} as currency.") + # or alternatively you can take an advantage of cur.execute() returning self. + for (country, currency) in cur.execute(SELECT): + print(f"{country} uses {currency} as currency.") + + # 2. Equivalently using fetchall(): + # This is potentially dangerous if result set is huge, as the whole result set is + # first materialized as list and then used for iteration. + cur.execute(SELECT) + for row in cur.fetchall(): + print(f"{row[0]} uses {row[1]} as currency.") + +``` + +!!! important + + Method `.Cursor.executemany()` is not intended for operations that return results, + so it does **NOT** returns `self` like `.Cursor.execute()`, and you can't use calls + to this method as iterator. + + + + +## Scrollable cursors + +SQL statements executed by `.Cursor.open()` have scrollable result set that could be +navigated using next methods: + +* `~.Cursor.fetch_next()` - Moves the cursor's current position to the next row and + returns it. Returns `None` if the cursor is empty or already positioned at the last row. + +* `~.Cursor.fetch_prior()` - Moves the cursor's current position to the prior row and + returns it. Returns `None` if the cursor is empty or already positioned at the first row. + +* `~.Cursor.fetch_first()` - Moves the cursor's current position to the first row and + returns it. Returns `None` if the cursor is empty. + +* `~.Cursor.fetch_last()` - Moves the cursor's current position to the last row and + returns it. Returns `None` if the cursor is empty. + +* `~.Cursor.fetch_absolute()` - Moves the cursor's current position to the specified + and returns the located row. Returns `None` if is beyond the + cursor's boundaries. + +* `~.Cursor.fetch_relative()` - Moves the cursor's current position backward or forward + by the specified and returns the located row. Returns `None` if the calculated + position is beyond the cursor's boundaries. + +!!! important + + Please note that scrollable cursors: + + a) are not supported by all versions of Firebird server. + + b) are internally materialized as a temporary record set, thus consuming + memory/disk resources, so this feature should be used only when really necessary. + +**Example:** + +```python +from firebird.driver import connect + +def print_row(row): + if row: + print(f"{row[0]}, {row[1]}, {row[2]}") + else: + print('NO DATA') + +with connect('employee', user='SYSDBA', password='masterkey') as con: + cur = con.cursor() + cur.open('select row_number() over (order by country), country, currency from country order by country') + + # You can iterate over scrollable cursors + for row in cur: + print_row(row) + + print('-' * 10) + # or fetch particular rows directly + print_row(cur.fetch_first()) + print_row(cur.fetch_last()) + print_row(cur.fetch_absolute(10)) + print_row(cur.fetch_next()) + print_row(cur.fetch_prior()) + print_row(cur.fetch_relative(-5)) + print_row(cur.fetch_relative(10)) + + print('-' * 10) + + cur.fetch_last() + print_row(cur.fetch_next()) + +``` + +**Sample output**: + +```text +1, Australia, ADollar +2, Austria, Euro +3, Belgium, Euro +4, Canada, CdnDlr +5, England, Pound +6, Fiji, FDollar +7, France, Euro +8, Germany, Euro +9, Hong Kong, HKDollar +10, Italy, Euro +11, Japan, Yen +12, Netherlands, Euro +13, Romania, RLeu +14, Russia, Ruble +15, Switzerland, SFranc +16, USA, Dollar +---------- +1, Australia, ADollar +16, USA, Dollar +10, Italy, Euro +11, Japan, Yen +10, Italy, Euro +5, England, Pound +15, Switzerland, SFranc +---------- +NO DATA + +``` + + + +## Parameterized statements + +When SQL command you want to execute contains data `values`, you can either: + +* Embed them `directly` or via `string formatting` into command string, e.g.: + + ```python + cur.execute("insert into the_table (a,b,c) values ('aardvark', 1, 0.1)") + # or + cur.execute("select * from the_table where col == 'aardvark'") + # or + cur.execute("insert into the_table (a,b,c) values ('%s', %i, %f)" % ('aardvark',1,0.1)) + # or + cur.execute(f"select * from the_table where col == '{value}'") + + ``` + +* Use parameter marker (`?`) in command string in the slots where values are expected, + then supply those values as Python list or tuple: + + ```python + cur.execute("insert into the_table (a,b,c) values (?,?,?)", ('aardvark', 1, 0.1)) + # or + cur.execute("select * from the_table where col == ?",('aardvark',)) + + ``` + +While both methods have the same results, the second one (called `parametrized`) has several +important advantages: + +* You don't need to handle conversions from Python data types to strings. +* Firebird-driver will handle all data type conversions (if necessary) from Python data types + to Firebird ones, including `None/NULL` conversion and conversion from `str` to `bytes` + in encoding expected by server. +* You may pass BLOB values as open `file-like` objects, and firebird-driver will handle the + transfer of BLOB value. + +Parametrized statemets also have some limitations. Currently: + +* `DATE`, `TIME` and `DATETIME` values must be relevant `datetime` objects. +* `NUMERIC` and `DECIMAL` values must be `decimal` objects. + + + + +## Prepared Statements + +Execution of any SQL statement has three phases: + +* *Preparation*: command is analyzed, validated, execution plan is determined + by optimizer and all necessary data structures (for example for input and output + parameters) are initialized. +* *Execution*: input parameters (if any) are passed to server and previously + prepared statement is actually executed by database engine. +* *Fetching*: result of execution and data (if any) are transferred from server + to client, and allocated resources are then released (by closing the statement). + +The preparation phase consumes some amount of server resources (memory and CPU). +Although preparation and release of resources typically takes only small amount +of CPU time, it builds up as number of executed statements grows. Firebird (like +most database engines) allows to spare this time for subsequent execution if +particular statement should be executed repeatedly - by reusing once prepared +statement for repeated execution. This may save significant amount of server +processing time, and result in better overall performance. + +Firebird-driver builds on this by encapsulating the Firebird SQL statement data +and related code into separate `.Statement` class, and implementing the `.Cursor` +class around it. The Cursor uses either an internally managed `.Statement` instance +to execute SQL commands provided as `string`, or uses `.Statement` instance +provided by your code as SQL command. + +To get the (prepared) `.Statement` instance for later (repeated) execution, use +`~.Cursor.prepare()` method. You can then pass this instance to `~.Cursor.execute()`, +`~.Cursor.executemany()` or `~.Cursor.open()` instead `command string`. + +`.Statement` instances are bound to `.Connection` instance, and can't be used +with any other `.Connection`. Beside repeated execution they are also useful +to get information about statement (like its execution `~.Statement.plan` or +`~.Statement.type`) before its execution. + +!!! note + + The internally managed `.Statement` instance is released when `.Cursor` is closed, + or before any new statement is executed. It means that if your code executes + the same SQL command (passed as string) repeatedly without closing the cursor + between calls, the same `.Statement` instance is (re)used. + +!!! important + + Implementation of Cursor in firebird-driver somewhat violates the Python DB API 2.0, + which requires that cursor will be unusable after call to `~.Cursor.close()`; and + an Error (or subclass) exception should be raised if any operation is attempted with + the cursor. In firebird-driver, the `.Cursor.close()` call only releases resources + associated with executed statement like the result set, and you can't fetch data or + query information about the SQL statement. However, you can use the cursor instance + to execute new SQL commands. + + !!! warning + + If you'll take advantage of this anomaly, your code would be less portable to other + Python DB API 2.0 compliant drivers. + +**Example:** + +```python +insertStatement = cur.prepare("insert into the_table (a,b,c) values (?,?,?)") + +inputRows = [ + ('aardvark', 1, 0.1), + ('zymurgy', 2147483647, 99999.999), + ('foobar', 2000, 9.9) + ] + +for row in inputRows: + cur.execute(insertStatement,row) +# +# or you can use executemany +# +cur.executemany(insertStatement, inputRows) + + +``` + +!!! info + `.Statement` for details. + + +## Named Cursors + +To allow the Python programmer to perform scrolling **UPDATE** or **DELETE** via the +**“SELECT ... FOR UPDATE”** syntax, the firebird-driver provides the read-only property +`.Cursor.name` and method `.Cursor.set_cursor_name()`. + +**Example Program:** + +```python +from firebird.driver import connect + +with connect('employee', user='sysdba', password='masterkey') as con: + curScroll = con.cursor() + curUpdate = con.cursor() + + curScroll.execute("select city from customer for update") + curScroll.set_cursor_name('city_scroller') + update = "update customer set city=? where current of " + curScroll.name + + for (city,) in curScroll: + city = ... # make some changes to city + curUpdate.execute( update, (city,) ) + + con.commit() + +``` + + +## Working with stored procedures + +Firebird stored procedures can have input parameters and/or output parameters. +Some databases support input/output parameters, where the same parameter is used +for both input and output; Firebird does not support this. + +It is important to distinguish between procedures that **return a result set** and +procedures that **populate and return their output parameters** exactly once. Conceptually, +the latter “return their output parameters” like a Python function, whereas the former +“yield result rows” like a Python generator. + +Firebird’s **server-side** procedural SQL syntax makes no such distinction, but client-side +SQL code (and C API code) must. A result set is retrieved from a stored procedure by +**SELECT'ing from the procedure, whereas output parameters are retrieved with an +'EXECUTE PROCEDURE' statement**. + +To **retrieve a result set** from a stored procedure with firebird-driver, use code +such as this: + +```python +cur.execute("select output1, output2 from the_proc(?, ?)", (input1, input2)) + +# Ordinary fetch code here, such as: +for row in cur: + ... # process row + +con.commit() # If the procedure had any side effects, commit them. + +``` + +To **execute** a stored procedure and **access its output parameters**, you can +choose from two options: + +1. Method `.Cursor.callproc()` that **conforms to Python DB API 2.0**. This method + does not returns the output parameters directly, and you must call `.Cursor.fetchone()` + **exactly once** to retrieve them. + +2. Method `.Cursor.call_procedure()` that returns output parameters directly + (or `None` if procedure does not have output parameters). + +**Examples:** + +```python +# Python DB API 2.0 compliant method: +cur.callproc("the_proc", (input1, input2)) +# If there are output parameters, retrieve them as though they were the +# first row of a result set... +outputParams = cur.fetchone() + +# alternative method: +outputParams = cur.call_procedure("the_proc", (input1, input2)) + +con.commit() # If the procedure had any side effects, commit them. + + +``` diff --git a/docs/docs/usage-guide/logging-driver-activities.md b/docs/docs/usage-guide/logging-driver-activities.md new file mode 100644 index 0000000..142bcf4 --- /dev/null +++ b/docs/docs/usage-guide/logging-driver-activities.md @@ -0,0 +1,207 @@ +# Logging driver activities + +The firebird-driver supports [context-based logging system](https://firebird-base.readthedocs.io/en/latest/logging/) +provided by [firebird-base](https://firebird-base.rtfd.io) package through use of `~firebird.base.logging.LoggingIdMixin`. + +Classes that use `~firebird.base.logging.LoggingIdMixin`: + +* `.Connection` - Internally used objects have `_logging_id_` set to 'Transaction.Main', + 'Transaction.Query' and 'Cursor.internal'. The log context is not defined. +* `.TransactionManager` - The `_logging_id_` is set to 'Transaction'. The + `~.TransactionManager.log_context()` is the `.Connection`. +* `.DistributedTransactionManager` - The `_logging_id_` is set to 'DTransaction'. The + `~.DistributedTransactionManager.log_context()` is `~firebird.base.types.UNDEFINED`. +* `.Statement` - The `~.Statement.log_context()` is `.Connection`. +* `.BlobReader` - The `~.Statement.log_context()` is the owning object or `~firebird.base.types.UNDEFINED`. +* `.Cursor` - The `~.Cursor.log_context()` is `.Connection`. +* `.Server` - The log context is not defined. + +**Example:** + +```python +import logging +from firebird.base.logging import get_logger, LogLevel +from firebird.driver import connect, driver_config + +# Helper function +def execute(cur: Cursor, cmd: str) -> None: + get_logger(cur).debug(f"Execute [{cmd=}]") + cur.execute(cmd) + +# Basic Python logging configuration +sh = logging.StreamHandler() +sh.setFormatter(logging.Formatter('%(levelname)-10s: [%(agent)s][%(context)s] %(message)s')) +logger = logging.getLogger() +logger.addHandler(sh) +logger.setLevel(LogLevel.DEBUG) + +# Firebird driver configuration +srv_cfg = """[local] +host = localhost +user = SYSDBA +password = masterkey +""" +driver_config.register_server('local', srv_cfg) +db_cfg = """[employee] +server = local +database = employee.fdb +protocol = inet +""" +driver_config.register_database('employee', db_cfg) + +print("Default logging ids") +with connect('employee') as con: + con_log = get_logger(con) + con_log.info('Start') + cur1 = con.cursor() + cur2 = con.cursor() + execute(cur1, 'select * from country') + execute(cur2, 'select * from project') + con_log.info('Stop') + +print("Custom logging ids") +with connect('employee') as con: + con._logging_id_ = 'employee-1' + con_log = get_logger(con) + con_log.info('Start') + cur1 = con.cursor() + cur1._logging_id_ = 'cursor-1' + cur2 = con.cursor() + cur2._logging_id_ = 'cursor-2' + execute(cur1, 'select * from country') + execute(cur2, 'select * from project') + con_log.info('Stop') + +``` + +Output: + +```text +Default logging ids +INFO : [Connection][UNDEFINED] Start +DEBUG : [Cursor][Connection] Execute [cmd='select * from country'] +DEBUG : [Cursor][Connection] Execute [cmd='select * from project'] +INFO : [Connection][UNDEFINED] Stop +Custom logging ids +INFO : [employee-1][UNDEFINED] Start +DEBUG : [cursor-1][employee-1] Execute [cmd='select * from country'] +DEBUG : [cursor-2][employee-1] Execute [cmd='select * from project'] +INFO : [employee-1][UNDEFINED] Stop + +``` +You can also trace the driver activities using [trace/audit for class instances](https://firebird-base.readthedocs.io/en/latest/trace/) +provided by [firebird-base](https://firebird-base.rtfd.io) package. + +**Example:** + +```python +import logging +from firebird.base.logging import get_logger, LogLevel +from firebird.base.trace import trace_manager, add_trace, trace_object, traced, TraceFlag +from firebird.driver import connect, driver_config +from firebird.driver.core import TransactionManager + +# Helper function +def execute(cur: Cursor, cmd: str) -> None: + cur.execute(cmd) + +# Basic Python logging configuration +sh = logging.StreamHandler() +sh.setFormatter(logging.Formatter('%(levelname)-10s: [%(agent)s][%(context)s] %(message)s')) +logger = logging.getLogger() +logger.addHandler(sh) +logger.setLevel(LogLevel.DEBUG) + +# Firebird driver configuration +srv_cfg = """[local] +host = localhost +user = SYSDBA +password = masterkey +""" +driver_config.register_server('local', srv_cfg) +db_cfg = """[employee] +server = local +database = employee.fdb +protocol = inet +""" +driver_config.register_database('employee', db_cfg) + +# Trace configuration +# First: register classes and methods that could be traced +trace_manager.register(Connection) +add_trace(Connection, 'close', traced) +trace_manager.register(TransactionManager) +add_trace(TransactionManager, 'begin', traced) +add_trace(TransactionManager, 'commit', traced) +add_trace(TransactionManager, 'rollback', traced) +trace_manager.register(Cursor) +add_trace(Cursor, 'execute', traced) +add_trace(Cursor, 'close', traced) +# Activate trace/audit +trace_manager.trace |= (TraceFlag.ACTIVE | TraceFlag.BEFORE | TraceFlag.AFTER | TraceFlag.FAIL) + +# Traced code +with connect('employee') as con: + trace_object(con) + trace_object(con.main_transaction) + con._logging_id_ = 'employee-1' + cur1 = con.cursor() + trace_object(cur1) + cur1._logging_id_ = 'cursor-1' + cur2 = con.cursor() + trace_object(cur2) + cur2._logging_id_ = 'cursor-2' + execute(cur1, 'select * from country') + execute(cur2, 'select * from project') + con.commit() + +``` + +Sample output: + +```text +DEBUG : [cursor-1][employee-1] >>> execute(operation='select * from country', parameters=None) +DEBUG : [Transaction.Main][employee-1] >>> begin(tpb=None) +DEBUG : [Transaction.Main][employee-1] <<< begin[0.00672] +DEBUG : [cursor-1][employee-1] >>> close() +DEBUG : [cursor-1][employee-1] <<< close[0.00004] +DEBUG : [cursor-1][employee-1] <<< execute[0.01119] Result: cursor-1 +DEBUG : [cursor-2][employee-1] >>> execute(operation='select * from project', parameters=None) +DEBUG : [cursor-2][employee-1] >>> close() +DEBUG : [cursor-2][employee-1] <<< close[0.00002] +DEBUG : [cursor-2][employee-1] <<< execute[0.00352] Result: cursor-2 +DEBUG : [Transaction.Main][employee-1] >>> commit(retaining=False) +DEBUG : [cursor-1][employee-1] >>> close() +DEBUG : [cursor-1][employee-1] <<< close[0.00017] +DEBUG : [cursor-2][employee-1] >>> close() +DEBUG : [cursor-2][employee-1] <<< close[0.00012] +DEBUG : [Transaction.Main][employee-1] <<< commit[0.00225] +DEBUG : [employee-1][UNDEFINED] >>> close() +DEBUG : [employee-1][UNDEFINED] <<< close[0.00764] + + +``` +If you will remove the `con.commit()` from the example above, the output will change to: + +```text +DEBUG : [cursor-1][employee-1] >>> execute(operation='select * from country', parameters=None) +DEBUG : [Transaction.Main][employee-1] >>> begin(tpb=None) +DEBUG : [Transaction.Main][employee-1] <<< begin[0.00338] +DEBUG : [cursor-1][employee-1] >>> close() +DEBUG : [cursor-1][employee-1] <<< close[0.00003] +DEBUG : [cursor-1][employee-1] <<< execute[0.00730] Result: cursor-1 +DEBUG : [cursor-2][employee-1] >>> execute(operation='select * from project', parameters=None) +DEBUG : [cursor-2][employee-1] >>> close() +DEBUG : [cursor-2][employee-1] <<< close[0.00003] +DEBUG : [cursor-2][employee-1] <<< execute[0.00345] Result: cursor-2 +DEBUG : [employee-1][UNDEFINED] >>> close() +DEBUG : [Transaction.Main][employee-1] >>> rollback(retaining=False, savepoint=None) +DEBUG : [cursor-1][employee-1] >>> close() +DEBUG : [cursor-1][employee-1] <<< close[0.00016] +DEBUG : [cursor-2][employee-1] >>> close() +DEBUG : [cursor-2][employee-1] <<< close[0.00014] +DEBUG : [Transaction.Main][employee-1] <<< rollback[0.00171] +DEBUG : [employee-1][UNDEFINED] <<< close[0.01001] + + +``` diff --git a/docs/docs/usage-guide/transanction-management.md b/docs/docs/usage-guide/transanction-management.md new file mode 100644 index 0000000..3cd953d --- /dev/null +++ b/docs/docs/usage-guide/transanction-management.md @@ -0,0 +1,574 @@ +# Transanction management + +For the sake of simplicity, firebird-driver lets the Python programmer ignore +transaction management to the greatest extent allowed by the Python Database +API Specification 2.0. The specification says, “if the database supports an +auto-commit feature, this must be initially off”. At a minimum, therefore, +it is necessary to call the commit method of the connection in order to persist +any changes made to the database. + +Remember that because of ACID, every data manipulation operation in the Firebird +database engine takes place in the context of a transaction, including operations +that are conceptually “read-only”, such as a typical SELECT. The client programmer +of firebird-driver establishes a transaction implicitly by using any SQL execution +method, such as `.Connection.execute_immediate()`, `.Cursor.execute()`, or +`.Cursor.callproc()`. + +Although firebird-driver allows the programmer to pay little attention to transactions, +it also exposes the full complement of the database engine’s advanced transaction +control features: [transaction parameters](transanction-management.md#transaction-parameters), [retaining transactions](transanction-management.md#retaining-transactions), [savepoints](transanction-management.md#savepoints), +and [distributed transactions](transanction-management.md#distributed-transactions). + +## Basics + +When it comes to transactions, Python Database API 2.0 specify that `.Connection` object +has to respond to the following methods: + +`.Connection.commit()` + + Commits any pending transaction to the database. Note that if the database supports + an auto-commit feature, this must be initially off. An interface method may be provided + to turn it back on. Database modules that do not support transactions should implement + this method with void functionality. + +`.Connection.rollback()` + + (optional) In case a database does provide transactions this method causes the the + database to roll back to the start of any pending transaction. **Closing a connection + without committing the changes first will cause an implicit rollback to be performed.** + +In addition to the implicit transaction initiation required by Python Database API, +firebird-driver allows the programmer to start transactions explicitly via the +`.Connection.begin()` method. Also `.Connection.savepoint()` method was added to provide +support for [Firebird SAVEPOINTs](http://www.firebirdsql.org/refdocs/langrefupd15-savepoint.html). + +But Python Database API 2.0 was created with assumption that connection can support only +one transactions per single connection. However, Firebird can support multiple independent +transactions that can run simultaneously within single connection / attachment to the +database. This feature is very important, as applications may require multiple transaction +opened simultaneously to perform various tasks, which would require to open multiple +connections and thus consume more resources than necessary. + +Firebird-driver surfaces this Firebird feature by separating transaction management out +from `.Connection` into separate `.TransactionManager` objects. To comply with Python DB +API 2.0 requirements, `.Connection` object uses one `.TransactionManager` instance as +`main transaction`, and delegates `~.Connection.begin()`, +`~.Connection.savepoint()`, `~.Connection.commit()`, `~.Connection.rollback()` and +`~.Connection.execute_immediate()` calls to it. + +!!! info + + More about using multiple transactions with the same connection in separate + [section](transanction-management.md#multiple_transactions). + +**Example:** + +```python +from firebird.driver import connect + +with connect('employee', user='SYSDBA', password='masterkey') as con: + cur = con.cursor() + + # Most minimalistic transaction management -> implicit start, only commit() and rollback() + # ======================================================================================== + # + # Transaction is started implicitly + cur.execute('insert into country values ('Oz','Crowns') + con.commit() # commits active transaction + # Again, transaction is started implicitly + cur.execute('insert into country values ('Barsoom','XXX') + con.rollback() # rolls back active transaction + cur.execute('insert into country values ('Pellucidar','Shells') + +# Commit was not performed before connection context was closed +# This will roll back the transaction because Python DB API 2.0 +# requires that closing connection with pending transaction must +# cause an implicit rollback + +``` + +!!! info + `.TransactionManager` for details. + + +## Auto-commit + +Firebird-driver doesn't support `auto-commit` feature directly, but developers +may achieve the similar result using `explicit` transaction start, taking advantage +of `.TransactionManager.default_action` and its default value (`~.DefaultAction.COMMIT`). + +**Example:** + +```python +from firebird.driver import connect + +with connect('employee', user='SYSDBA', password='masterkey') as con: + cur = con.cursor() + + con.begin() + cur.execute('insert into country values ('Oz','Crowns') + con.begin() # commits active transaction and starts new one + cur.execute('insert into country values ('Barsoom','XXX') + con.begin() # commits active transaction and starts new one + cur.execute('insert into country values ('Pellucidar','Shells') + + # However, commit is required before connection is closed, + # because Python DB API 2.0 requires that closing connection + # with pending transaction must cause an implicit rollback + con.commit() + +``` + + +## Transaction parameters + +The database engine offers the client programmer an optional facility called +`transaction parameter buffers` (TPBs) for tweaking the operating characteristics +of the transactions he initiates. These include characteristics such as whether +the transaction has read and write access to tables, or read-only access, and +whether or not other simultaneously active transactions can share table access +with the transaction. + +Transaction manager has `~.TransactionManager.default_tpb` attribute that can be +changed to set the default TPB to be used for all subsequent transactions started +by this manager. Also Connection have a `~.Connection.default_tpb` attribute, +but it's used to set the default TPB for all transactions managers subsequently +created for the connection (see `.Connection.transaction_manager()`). + +Alternatively, if the programmer only wants to set the TPB for a single transaction, +he can start a transaction explicitly via the `.Connection.begin()` or +`.TransactionManager.begin()` method and pass a TPB for that single transaction. + +The TPB is a `bytes` value constructed from various tags and binary values, as +defined by API. While you can construct the TPB manually, the firebird-driver +provides several convenient ways for TPB construction: + +1. The `.tpb()` function for simple TPBs. + +2. The `~firebird.driver.core.TPB` class for complex TPBs (including table reservation etc.). + +**Examples:** + +```python +from firebird.driver import tpb, TPB, Isolation, TraAccessMode, TableShareMode, TableAccessMode + +# Use tpb() if isolation, timeout and access_mode parameters are enough for you +simple_tpb = tpb(Isolation.READ_COMMITTED_READ_CONSISTENCY,100,TraAccessMode.WRITE) + +# Use TPB if you want additional parameters than isolation, timeout and access_mode +my_tpb = TPB(isolation=Isolation.SNAPSHOT, + access_mode=TraAccessMode.WRITE, + lock_timeout=100, + no_auto_undo=True, + auto_commit=True, + ignore_limbo=True) +my_tpb.reserve_table('MY_TABLE', TableShareMode.PROTECTED, TableAccessMode.LOCK_WRITE) +complex_tpb = my_tpb.get_buffer() + +``` + + +## Getting information about transaction + +!!! important + + Because the scope and type of transaction information depends on the version of the Firebird + server, this information is made available through a separate class + `.TransactionInfoProvider`. The `.TransactionManager.info` property provides access to + instance of `.TransactionInfoProvider` or it's **ancestor** class according to used + Firebird version. + +Although you may query the information directly from server using +`~.TransactionInfoProvider3.get_info()` method (that wraps the Firebird `ITransaction.getInfo()` +API call), the `.TransactionInfoProvider` object provides more convenient methods and properties +for obtaining specific information directly. + +**Example:** + +```python +from firebird.driver import connect, driver_config + +driver_config.server_defaults.host.value = 'localhost' +with connect('employee', user='SYSDBA', password='masterkey') as con: + con.begin() + info = con.main_transaction.info + print(f"Transaction ID: {info.id}") + print(f"Database: {info.database}") + print(f"Isolation level: {info.isolation!s}") + print(f"Lock timeout: {info.lock_timeout}") + print(f"Is Read-Only: {info.is_read_only()}") + print(f"ID of Oldest Interesting Transaction: {info.oit}") + print(f"ID of Oldest Active Transaction: {info.oat}") + print(f"ID of Oldest Snapshot Transaction: {info.ost}") + +``` + +Output: + +```text +Transaction ID: 352 +Database: localhost:employee +Isolation level: Isolation.SNAPSHOT +Lock timeout: -1 +Is Read-Only: False +ID of Oldest Interesting Transaction: 350 +ID of Oldest Active Transaction: 352 +ID of Oldest Snapshot Transaction: 352 + +``` + +## Retaining transactions + +The `~.TransactionManager.commit()` and `~.TransactionManager.rollback()` methods +accept an optional boolean keyword parameter `retaining` (**default False**) to +indicate whether to recycle the transactional context of the transaction being resolved +by the method call. + +If retaining is `True`, the infrastructural support for the transaction active at +the time of the method call will be “retained” (efficiently and transparently recycled) +after the database server has committed or rolled back the conceptual transaction. + +!!! important + + In code that commits or rolls back frequently in short amount of time (like in loop), + “retaining” the transaction may yield better performance. However, retaining transactions + must be used cautiously because they can interfere with the server’s ability to garbage + collect old record versions. For details about this issue, read the “Garbage” section of + [this document](http://www.ibphoenix.com/resources/documents/search/doc_21) by Ann Harrison. + + It's definitely no recommended to use retaining for all transactions, or retain the transaction + context indefinitely (you should eventually commit/rollback the transaction in normal + way). + +For more information about retaining transactions, see `Firebird documentation`. + + +## Savepoints + +Savepoints are named, intermediate control points within an open transaction that +can later be rolled back to, without affecting the preceding work. Multiple savepoints +can exist within a single unresolved transaction, providing “multi-level undo” functionality. + +Although Firebird savepoints are fully supported from SQL alone via the `SAVEPOINT ‘name’` +and `ROLLBACK TO ‘name’` statements, firebird-driver also exposes savepoints at the Python +API level for the sake of convenience. + +Call to method `.TransactionManager.savepoint()` establishes a savepoint with the specified +`name`. To roll back to a specific savepoint, call the `~.TransactionManager.rollback()` +method and provide the name of the savepoint for the `savepoint` keyword parameter. If the +savepoint parameter of `~.TransactionManager.rollback()` is not specified, the active +transaction is cancelled in its entirety, as required by the Python Database API Specification. + +The following program demonstrates savepoint manipulation via the firebird-driver API, +rather than raw SQL. + +```python +from firebird.driver import connect + +with connect('employee', user='SYSDBA', password='masterkey') as con: + cur = con.cursor() + + cur.execute("recreate table test_savepoints (a integer)") + con.commit() + + print('Before the first savepoint, the contents of the table are:') + cur.execute("select * from test_savepoints") + print(' ', cur.fetchall()) + + cur.execute("insert into test_savepoints values (?)", [1]) + con.savepoint('A') + print('After savepoint A, the contents of the table are:') + cur.execute("select * from test_savepoints") + print(' ', cur.fetchall()) + + cur.execute("insert into test_savepoints values (?)", [2]) + con.savepoint('B') + print('After savepoint B, the contents of the table are:') + cur.execute("select * from test_savepoints") + print(' ', cur.fetchall()) + + cur.execute("insert into test_savepoints values (?)", [3]) + con.savepoint('C') + print('After savepoint C, the contents of the table are:') + cur.execute("select * from test_savepoints") + print(' ', cur.fetchall()) + + con.rollback(savepoint='B') + print('After rolling back to savepoint B, the contents of the table are:') + cur.execute("select * from test_savepoints") + print(' ', cur.fetchall()) + + con.rollback() + print('After rolling back entirely, the contents of the table are:') + cur.execute("select * from test_savepoints") + print(' ', cur.fetchall()) + +``` + +The output of the example program is shown below: + +```text +Before the first savepoint, the contents of the table are: + [] +After savepoint A, the contents of the table are: + [(1,)] +After savepoint B, the contents of the table are: + [(1,), (2,)] +After savepoint C, the contents of the table are: + [(1,), (2,), (3,)] +After rolling back to savepoint B, the contents of the table are: + [(1,), (2,)] +After rolling back entirely, the contents of the table are: + [] + +``` + + + +## Using multiple transactions with the same connection + +To use additional transactions that could run simultaneously with +`main transaction` managed by `.Connection`, +create new `.TransactionManager` object calling `.Connection.transaction_manager()` +method. If you don't specify the optional `default_tpb` parameter, this new +`.TransactionManager` inherits the `~.Connection.default_tpb` from `.Connection`. +Physical transaction is not started when `.TransactionManager` instance is +created, but implicitly when first SQL statement for cursor created from +this manager is executed, or explicitly via `.TransactionManager.begin()` call. + +To execute statements in context of this additional transaction you have to +use `cursors` obtained directly from this `.TransactionManager` instance calling +its `~.TransactionManager.cursor()` method, or call `.TransactionManager.execute_immediate()` +method. + +**Example:** + +```python +from firebird.driver import connect, tpb, Isolation, TraAccessMode + +with connect('employee', user='SYSDBA', password='masterkey') as con: + # Cursor for main_transaction context + cur = con.cursor() + + # Create new READ ONLY READ COMMITTED transaction + ro_transaction = con.transaction_manager(tpb(Isolation.READ_COMMITTED_RECORD_VERSION, + access=TraAccessMode.READ)) + # and cursor + ro_cur = ro_transaction.cursor() + + cur.execute('insert into country values ('Oz','Crowns') + con.commit() # commits main transaction + + # Read data created by main transaction from second one + ro_cur.execute("select * from COUNTRY where COUNTRY = `Oz`") + print(ro_cur.fetchall()) + + # Insert more data, but don't commit + cur.execute('insert into country values ('Barsoom','XXX') + + # Read data created by main transaction from second one + ro_cur.execute("select * from COUNTRY where COUNTRY = `Barsoom`") + print(ro_cur.fetchall()) + +``` + + + + +## Distributed Transactions + +Distributed transactions are transactions that span multiple databases. +Firebird-driver provides this Firebird feature through `.DistributedTransactionManager` +class. Instances of this class must be created manually, and managed transactions +are fully independent from all other transactions, main or secondary, of member connections. + +Similarly to `.TransactionManager`, distributed transactions are managed +through `~.DistributedTransactionManager.begin()`, +`~.DistributedTransactionManager.savepoint()`, `~.DistributedTransactionManager.commit()` +and `~.DistributedTransactionManager.rollback()` methods. +Additionally, `.DistributedTransactionManager` exposes method +`~.DistributedTransactionManager.prepare()` that explicitly initiates the +first phase of `Two-Phase Commit Protocol`. Transaction parameters are defined +similarly to `.TransactionManager` using `~.DistributedTransactionManager.default_tpb` +or as optional parameter to `~.DistributedTransactionManager.begin()` call. + +SQL statements that should belong to context of distributed transaction are +executed via `.Cursor` instances aquired through `.DistributedTransactionManager.cursor()` +method, or calling `.DistributedTransactionManager.execute_immediate()` method. + +!!! note + + Because `.Cursor` instances can belong to only one `.Connection`, the + `~.DistributedTransactionManager.cursor()` method has mandatory parameter + `connection`, to specify to which member connection cursor should belong. + + The `~.DistributedTransactionManager.execute_immediate()` method operates + on **all** databases in *group*. + +**Example program:** + +```python +from firebird.driver import create_database, DistributedTransactionManager + +# First database +con1 = create_database('db1.fdb', user='SYSDBA', password='masterkey') +con1.execute_immediate("recreate table T (PK integer, C1 integer)") +con1.commit() + +# Second database +con2 = create_database('db2.fdb', user='SYSDBA', password='masterkey') +con2.execute_immediate("recreate table T (PK integer, C1 integer)") +con2.commit() + +# Create distributed transaction manager +dt = DistributedTransactionManager((con1,con2)) + +# Prepare cursors for each connection +dc1 = dt.cursor(con1) +dc2 = dt.cursor(con2) + +# Connection cursors to check content of databases +q = 'select * from T order by pk' + +cc1 = con1.cursor() +p1 = cc1.prep(q) + +cc2 = con2.cursor() +p2 = cc2.prep(q) + +print("Distributed transaction: COMMIT") +# =============================== +dc1.execute('insert into t (pk) values (1)') +dc2.execute('insert into t (pk) values (1)') +dt.commit() + +# check it +con1.commit() +cc1.execute(p1) +print('db1:', cc1.fetchall()) +con2.commit() +cc2.execute(p2) +print('db2:', cc2.fetchall()) + +print("Distributed transaction: PREPARE + COMMIT") +# ========================================= +dc1.execute('insert into t (pk) values (2)') +dc2.execute('insert into t (pk) values (2)') +dt.prepare() +dt.commit() + +# check it +con1.commit() +cc1.execute(p1) +print('db1:', cc1.fetchall()) +con2.commit() +cc2.execute(p2) +print('db2:', cc2.fetchall()) + +print("Distributed transaction: SAVEPOINT + ROLLBACK to it") +# =================================================== +dc1.execute('insert into t (pk) values (3)') +dt.savepoint('CG_SAVEPOINT') +dc2.execute('insert into t (pk) values (3)') +dt.rollback(savepoint='CG_SAVEPOINT') + +# check it - via group cursors, as transaction is still active +dc1.execute(q) +print('db1:', dc1.fetchall()) +dc2.execute(q) +print('db2:', dc2.fetchall()) + +print("Distributed transaction: ROLLBACK") +# ================================= +dt.rollback() + +# check it +con1.commit() +cc1.execute(p1) +print('db1:', cc1.fetchall()) +con2.commit() +cc2.execute(p2) +print('db2:', cc2.fetchall()) + +print("Distributed transaction: EXECUTE_IMMEDIATE") +# ========================================== +dt.execute_immediate('insert into t (pk) values (3)') +dt.commit() + +# check it +con1.commit() +cc1.execute(p1) +print('db1:', cc1.fetchall()) +con2.commit() +cc2.execute(p2) +print('db2:', cc2.fetchall()) + +# Finalize +con1.drop_database() +con1.close() +con2.drop_database() +con2.close() + +``` + +Output: + +```text +Distributed transaction: COMMIT +db1: [(1, None)] +db2: [(1, None)] +Distributed transaction: PREPARE + COMMIT +db1: [(1, None), (2, None)] +db2: [(1, None), (2, None)] +Distributed transaction: SAVEPOINT + ROLLBACK to it +db1: [(1, None), (2, None), (3, None)] +db2: [(1, None), (2, None)] +Distributed transaction: ROLLBACK +db1: [(1, None), (2, None)] +db2: [(1, None), (2, None)] +Distributed transaction: EXECUTE_IMMEDIATE +db1: [(1, None), (2, None), (3, None)] +db2: [(1, None), (2, None), (3, None)] + +``` + + + +## Transaction Context Manager + +Firebird-driver provides context manager `~firebird.driver.core.transaction` that allows automatic +transaction management using WITH statement. It can work with +any object that supports `begin()`, `commit()` and `rollback()` methods, i.e. +`.Connection`, `.TransactionManager` or `.DistributedTransactionManager`. + +It starts transaction when WITH block is entered and commits it if no exception +occurs within it, or calls `rollback()` otherwise. Exceptions raised in WITH +block are never suppressed. + +Examples: + +```python +from firebird.driver import connect, transaction, DistributedTransactionManager + +with connect('employee', user='SYSDBA', password='masterkey') as con: + + # Uses default main transaction + with transaction(con): + cur = con.cursor() + cur.execute("insert into T (PK,C1) values (1,'TXT')") + + # Uses separate transaction + with transaction(con.transaction_manager()) as tr: + cur = tr.cursor() + cur.execute("insert into T (PK,C1) values (2,'AAA')") + + # Uses distributed transaction + with connect('employee2', user='SYSDBA', password='masterkey') as con2, + DistributedTransactionManager(con, con2) as dtm: + with transaction(dtm): + cur1 = cg.cursor(con) + cur2 = cg.cursor(con2) + cur1.execute("insert into T (PK,C1) values (3,'Local')") + cur2.execute("insert into T (PK,C1) values (3,'Remote')") + +``` diff --git a/docs/docs/usage-guide/working-with-services.md b/docs/docs/usage-guide/working-with-services.md new file mode 100644 index 0000000..ca757ae --- /dev/null +++ b/docs/docs/usage-guide/working-with-services.md @@ -0,0 +1,668 @@ + + +# Working with Services + +Database server maintenance tasks such as user management, load monitoring, +and database backup have traditionally been automated by scripting the +command-line tools `gbak`, `gfix`, `gsec`, and `gstat`. + +The API presented to the client programmer by these utilities is inelegant +because they are, after all, command-line tools rather than native components +of the client language. To address this problem, Firebird has a facility called +the `Services API`, which exposes a uniform interface to the administrative +functionality of the traditional command-line tools. + +The native Services API, though consistent, is much lower-level than a Pythonic API. +If the native version were exposed directly, accomplishing a given task would probably +require more Python code than scripting the traditional command-line tools. For this +reason, the firebird-driver presents its own abstraction over the native API. + + +## Services API Connections + +All Services API operations are performed in the context of a `connection` to a specific +database server, represented by the `.Server` class. Similarly to database connections, +firebird-driver provides `.connect_server()` constructor function to create such connections. + +This constructor has one positional and several keyword parameters. + +The value of `server` positional parameter must be one of: + +* name of registered server configuration +* server host name or address + +Keyword parameters are intended to override selected configuration options, or to specify +options that are not configurable. + +A simple server connection is typically established with code such as this: + +```python +from firebird.driver import connect_server + +# Attach to 'embedded' server +srv = connect_server('', user='SYSDBA', password='masterkey') + +# Attach to 'local' server +srv = connect_server('localhost', user='SYSDBA', password='masterkey') + +# Set 'user' and 'password' via configuration +from firebird.driver import driver_config +driver_config.server_defaults.user.value = 'SYSDBA' +driver_config.server_defaults.password.value = 'masterkey' +srv = connect_server('localhost') + +``` + +However, it's recommended to use specific configuration for servers. +It's possible to register servers directly in code like this: + +```python +from firebird.driver import connect_server, driver_config + +# Register Firebird server +srv_cfg = """[main_server] +host = 192.168.0.15 +user = SYSDBA +password = Xyzzy +""" +driver_config.register_server('main_server', srv_cfg) + +# Attach to 'main' server +con = connect('main_server') + +``` + +But more convenient approach is using single configuration file: + +```text +# file: myapp.cfg + +[firebird.driver] +servers = main_server +databases = employee + +[main_server] +host = 192.168.0.15 +user = SYSDBA +password = Xyzzy + +``` + +```python +from firebird.driver import connect_server, driver_config + +driver_config.read('myapp.cfg') + +# Attach to 'main' server +con = connect('main_server') + +``` + +!!! note + + Like database connections, it's important to properly `~Server.close()` them + when you don't need them anymore. + +`.Server` object provides main infrastructure for communication with Firebird server services, +and manages number of objects that provide actual server services: + +* The `.Server.info` property object provides [Server Configuration and State information](working-with-services.md#server-configuration-and-state-information). +* The `.Server.database` property object provides [Database options](working-with-services.md#database-options) and [Database maintenance](working-with-services.md#database-maintenance). +* The `.Server.user` property object provides [User maintenance](working-with-services.md#user-maintenance). +* The `.Server.trace` property object provides management of [Trace sessions](working-with-services.md#trace-sessions). + +!!! info + `.connect_server()` and `.Server` for details. + + +## Text output from Services + +Some services like `.ServerDbServices.backup()` may return significant amount of text. +Rather than return the whole text as single string value by methods that provide access +to these services, firebird-driver isolated the transfer process to separate methods: + +* `~.Server.readline()` - Similar to `file.readline`, returns next line of output from Service. +* `~.Server.readline_timed()` - Like `~.Server.readline()` but with timeout. +* `~.Server.readlines()` - Like `file.readlines`, returns list of output lines. +* Iteration over `.Server` object, because `.Server` has built-in support for [iterator protocol](https://docs.python.org/3/library/stdtypes.html#iterator-types). +* Using `callback` method provided by developer. Each `.Server` method that returns its result + asynchronously accepts an optional parameter `callback`, which must be a function that accepts + one string parameter. This method is then called with each output line coming from service. +* `~.Server.wait()` - Waits for Sevice to finish, ignoring rest of the output it may produce. + +!!! important + + The Firebird server sends text output from services as packets, that could have two forms. + The method for packet construction used for text transfer is controlled by `.Server.mode` + attribute with next possible values: + + 1. `.SrvInfoCode.LINE` : A single line of text. + 2. `.SrvInfoCode.TO_EOF` : A block of text up to specified (buffer) size. + + Both methods have specific pros and cons: + + 1. `~.SrvInfoCode.LINE` means more roundtrips and thus slower transfer of service output, + but each line is sent to client immediately when it's available. + 2. `~.SrvInfoCode.TO_EOF` means fewer roundtrips so large output is transferred quickly, + but service output is not sent until the transfer buffer is not full, or service stops. + + **The default mode is** `~.SrvInfoCode.TO_EOF` **with 64K buffer.** + +!!! warning + + Until output is not fully fetched from service, any attempt to start another asynchronous + service will fail with exception! This constraint is set by Firebird Service API. + + You may check the status of asynchronous Services using `.Server.is_running()` method. + + In cases when you're not interested in output produced by Service, call `~.Server.wait()` + to wait for service to complete. + +!!! important + + Normally, requesting output with `~.Server.readline()` blocks until any output is + available from server. Bacuse this method is used by iteration over `.Server` and + `~.Server.readlines()` method, they will block as well. Most services produce output + continuously and without (much) delay, so this is usually not a problem. However, some + services (eg trace) can produce output at significantly slower intervals (if at all), + which complicates the creation of responsive applications. In this case, it is necessary + to use the `~.Server.readline_timed()` method, which allows you to limit the waiting + time for the output. + +**Examples:** + +```python +from firebird.driver import connect_server +with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + print("Fetch materialized") + print("==================") + print("Start backup") + srv.database.backup(database='employee', backup='employee.fbk') + print("srv.running is", srv.isrunning()) + report = srv.readlines() + print(f"{len(report)} lines returned") + print("First 5 lines from output:") + for i in xrange(5): + print(i,report[i]) + print("srv.running is", srv.isrunning()) + print() + print("Iterate over result") + print("===================") + srv.database.backup(database='employee', backup='employee.fbk') + output = [] + for line in srv: + output.append(line) + print(f"{len(output)} lines returned") + print("Last 5 lines from output:") + for line in output[-5:]: + print(line) + print() + print("Callback") + print("========") + + output = [] + + # Callback function + def fetchline(line): + output.append(line) + + srv.database.backup(database='employee', backup='employee.fbk', callback=fetchline) + print(f"{len(output)} lines returned") + print("Last 5 lines from output:") + for line in output[-5:]: + print(line) + +``` + +Output: + +```text +Fetch materialized +================== +Start backup +svc.running is True +558 lines returned +First 5 lines from output: +0 gbak:readied database employee for backup +1 gbak:creating file employee.fbk +2 gbak:starting transaction +3 gbak:database employee has a page size of 4096 bytes. +4 gbak:writing domains +svc.running is False + +Iterate over result +=================== +558 lines returned +Last 5 lines from output: +gbak:writing referential constraints +gbak:writing check constraints +gbak:writing SQL roles +gbak:writing names mapping +gbak:closing file, committing, and finishing. 74752 bytes written + +Callback +======== +558 lines returned +Last 5 lines from output: +gbak:writing referential constraints +gbak:writing check constraints +gbak:writing SQL roles +gbak:writing names mapping +gbak:closing file, committing, and finishing. 74752 bytes written + +``` + +## Server Configuration and State information + +!!! important + + Because the scope and type of service information depends on the version of the Firebird + server, this information is made available through a separate class + `.ServerInfoProvider`. The `.Server.info` property provides access to + instance of `.ServerInfoProvider` or it's **ancestor** class according to attached + Firebird server version. + +`.ServerInfoProvider` methods and properties: + +* `~.ServerInfoProvider.get_log()` - Request the contents of the server’s log file (`firebird.log`). + + This method is so-called `Async service` that only initiates log transfer. Actual log + content could be read by one from many methods for [text output from Services](working-with-services.md#text-output-from-services) that + `.Server` provides . + +* `~.ServerInfoProvider.version` - Returns Firebird server version as SEMVER string. + +* `~.ServerInfoProvider.engine_version` - Firebird server version as . float value. + +* `~.ServerInfoProvider.manager_version` - Firebird service manager version. + +* `~.ServerInfoProvider.architecture` - Firebird server implementation description. + +* `~.ServerInfoProvider.home_directory` - Firebird server home directory. + +* `~.ServerInfoProvider.security_database` - Security database. + +* `~.ServerInfoProvider.lock_directory` - Directory with lock file(s). + +* `~.ServerInfoProvider.message_directory` - Directory with message file(s). + +* `~.ServerInfoProvider.capabilities` - Firebird server capabilities (as `.ServerCapability` flags). + +* `~.ServerInfoProvider.connection_count` - Current number of database attachments. + +* `~.ServerInfoProvider.attached_databases` - List of attached databases. + +**Example:** + +```python +from firebird.driver import driver_config, connect, connect_server + +srv_cfg = """[local] +host = localhost +user = SYSDBA +password = masterkey +""" +driver_config.register_server('local', srv_cfg) +db_cfg = """[employee] +server = local +database = employee.fdb +protocol = inet +""" +driver_config.register_database('employee', db_cfg) +with connect('employee', user='SYSDBA', password='masterkey'), connect_server('local', user='SYSDBA', password='masterkey') as srv: + print(f'{srv.info.version=}') + print(f'{srv.info.engine_version=}') + print(f'{srv.info.manager_version=}') + print(f'{srv.info.architecture=}') + print(f'{srv.info.home_directory=}') + print(f'{srv.info.security_database=}') + print(f'{srv.info.lock_directory=}') + print(f'{srv.info.message_directory=}') + print(f'{srv.info.capabilities=!s}') + print(f'{srv.info.connection_count=}') + print(f'{srv.info.attached_databases=}') + +``` + +Sample output for 64-bit Linux Firebird 4.0 Beta 2: + +```text +srv.info.version='4.0.0.1963' +srv.info.engine_version=4.0 +srv.info.manager_version=2 +srv.info.architecture='Firebird/Linux/AMD/Intel/x64' +srv.info.home_directory='/opt/firebird/' +srv.info.security_database='/opt/firebird/security4.fdb' +srv.info.lock_directory='/tmp/firebird/' +srv.info.message_directory='/opt/firebird/' +srv.info.capabilities=ServerCapability.REMOTE_HOP|MULTI_CLIENT +srv.info.connection_count=1 +srv.info.attached_databases=['/opt/firebird/examples/empbuild/employee.fdb'] + +``` + +## Database options + +Database options could be set using `.ServerDbServices` instance accessible via +`.Server.database` property. + +* `~.ServerDbServices.set_default_cache_size()` - Sets individual page cache size for database. + + ```python + >>> from firebird.driver import connect_server + >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + >>> srv.database.set_default_cache_size(database='employee.fdb', size=5000) + + ``` + +* `~.ServerDbServices.set_sweep_interval()` - Sets database sweep interval. + + ```python + >>> from firebird.driver import connect_server + >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + >>> srv.database.set_sweep_interval(database='employee.fdb', interval=100000) + + ``` + +* `~.ServerDbServices.set_space_reservation()` - Sets space reservation option for database. + + ```python + >>> from firebird.driver import connect_server, DbSpaceReservation + >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + >>> srv.database.set_space_reservation(database='employee.fdb', mode=DbSpaceReservation.USE_FULL) + + ``` + +* `~.ServerDbServices.set_write_mode()` - Sets database write mode (SYNC/ASYNC). + + ```python + >>> from firebird.driver import connect_server, DbWriteMode + >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + >>> srv.database.set_write_mode(database='employee.fdb', mode=DbWriteMode.ASYNC) + + ``` + +* `~.ServerDbServices.set_access_mode()` - Sets database access mode (R/W or R/O). + + ```python + >>> from firebird.driver import connect_server, DbAccessMode + >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + >>> srv.database.set_access_mode(database='employee.fdb', mode=DbAccessMode.READ_ONLY) + + ``` + +* `~.ServerDbServices.set_sql_dialect()` - Sets database SQL dialect. + + !!! warning + + Changing SQL dialect on existing database is not recommended. Only newly created + database objects would respect new dialect setting, while objects created with + previous dialect remain unchanged. That may have dire consequences. + + ```python + >>> from firebird.driver import connect_server + >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + >>> srv.database.set_sql_dialect(database='employee.fdb', dialect=1) + + ``` + +* `~.ServerDbServices.no_linger()` - Sets one-off override for database linger. + + ```python + >>> from firebird.driver import connect_server + >>> with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + >>> srv.database.no_linger(database='employee.fdb') + + ``` + + +## Database maintenance + +!!! important + + Because available database-related actions depends on the version of the Firebird + server, they are made available through a separate class `.ServerDbServices`. + The `.Server.database` property provides access to instance of `.ServerDbServices` or + it's **ancestor** class according to attached Firebird server version. + +* `~.ServerDbServices3.get_statistics()` - Returns database statistics produced by gstat + utility. + + This method is so-called `Async service` that only initiates report processing. Actual + report content could be read by one from many methods for [text output from Services](working-with-services.md#text-output-from-services) that + `.Server` provides . + + ```python + from firebird.driver import connect_server, SrvStatFlag + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.get_statistics(database='employee.fdb', + flags=SrvStatFlag.DATA_PAGES | SrvStatFlag.RECORD_VERSIONS), + tables=['EMPLOYEE','PROJECT']) + stats = srv.readlines() + + ``` + +* `~.ServerDbServices3.backup()` - Performs logical (GBAK) database backup. + + This method is so-called `Async service` that only initiates the backup process. Output + from gbak could be read by one from many methods for [text output from Services](working-with-services.md#text-output-from-services) that + `.Server` provides . + + ```python + from firebird.driver import connect_server, SrvBackupFlag + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.backup(database='employee.fdb', + backup='/backup/employee.fbk', + flags=SrvBackupFlag.IGNORE_CHECKSUMS | SrvBackupFlag.NO_GARBAGE_COLLECT, + stats='TD', verbose=True) + report = srv.readlines() + + ``` + +* `~.ServerDbServices3.local_backup()` - Performs logical (GBAK) database backup into local byte + stream. + + ```python + from firebird.driver import connect_server, SrvBackupFlag + f = open('/backup/employee.fbk',mode='wb') + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.local_backup(database='employee.fdb', backup_stream=f, + flags=SrvBackupFlag.IGNORE_CHECKSUMS | SrvBackupFlag.NO_GARBAGE_COLLECT) + f.close() + + ``` + +* `~.ServerDbServices3.restore()` - Performs database restore from logical (GBAK) backup. + + This method is so-called `Async service` that only initiates the restore process. Output + from gbak could be read by one from many methods for [text output from Services](working-with-services.md#text-output-from-services) that + `.Server` provides . + + ```python + from firebird.driver import connect_server, SrvRestoreFlag + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.restore(backup='/backup/employee.fbk', + database='/data/employee.fdb', + flags=SrvRestoreFlag.REPLACE, + stats='TD', verbose=True, page_size=8192) + report = srv.readlines() + + ``` + +* `~.ServerDbServices3.local_restore()` - Performs database restore from logical (GBAK) backup + stored in local byte stream. + + ```python + from firebird.driver import connect_server, SrvRestoreFlag + f = open('/backup/employee.fbk',mode='rb') + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.local_restore(backup_stream=f, database='/data/employee.fdb', + flags=SrvRestoreFlag.REPLACE, page_size=8192) + f.close() + + ``` + +* `~.ServerDbServices3.nbackup()` - Performs physical (NBACKUP) database backup. + + ```python + from firebird.driver import connect_server + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.nbackup(database='employee.fdb', backup='/backup/employee.bkp1', level=1) + + ``` + +* `~.ServerDbServices3.nrestore()` - Performs restore from physical (NBACKUP) database + backup. + + ```python + from firebird.driver import connect_server + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.nrestore(backups=['/backup/employee.bkp0', '/backup/employee.bkp1'], + database='/data/employee.fdb') + + ``` + +* `~.ServerDbServices3.shutdown()` - Database shutdown. + + ```python + from firebird.driver import connect_server, ShutdownMode, ShutdownMethod + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.shutdown(database='employee.fdb', mode=ShutdownMode.SINGLE, + method=ShutdownMethod.FORCED, timeout=10) + + ``` + +* `~.ServerDbServices3.bring_online()` - Bring previously shut down database back online. + + ```python + from firebird.driver import connect_server, OnlineMode + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.bring_online(database='employee.fdb', mode=OnlineMode.MULTI) + + ``` + +* `~.ServerDbServices3.sweep()` - Performs database sweep operation. + + ```python + from firebird.driver import connect_server + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.sweep(database='employee.fdb') + + ``` + +* `~.ServerDbServices3.validate()` - Performs database validation. + + This method is so-called `Async service` that only initiates the validation process. Output + from validation could be read by one from many methods for [text output from Services](working-with-services.md#text-output-from-services) that + `.Server` provides . + + ```python + from firebird.driver import connect_server + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.validate(database='employee.fdb') + report = srv.readlines() + + ``` + +* `~.ServerDbServices3.repair()` - Performs database repair operation. + + ```python + from firebird.driver import connect_server, SrvRepairFlag + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + srv.database.repair(database='employee.fdb', + flags=SrvRepairFlag.REPAIR | SrvRepairFlag.KILL_SHADOWS) + + ``` + +* `~.ServerDbServices3.get_limbo_transaction_ids()` - Returns list of transactions in limbo. + +* `~.ServerDbServices3.commit_limbo_transaction()` - Resolves limbo transaction with commit. + +* `~.ServerDbServices3.rollback_limbo_transaction()` - Resolves limbo transaction with rollback. + +* `~.ServerDbServices.nfix_database` - Fixup database after filesystem copy. + +* `~.ServerDbServices.set_replica_mode` - Manage replica database. + + +## User maintenance + +!!! important + + Because user maintenance functionality may depend on the version of the Firebird + server, this functionality is made available through a separate class + `.ServerUserServices`. The `.Server.user` property provides access to + instance of `.ServerUserServices` or it's **ancestor** class according to attached + Firebird server version. + +!!! tip + + Since Firebird 2.5 you can use SQL commands (CREATE/ALTER/DROP USER) to manage users in + a security database from a regular database attachment. + + The SQL set of DDL commands for managing user accounts has been further enhanced in Firebird 3, + thus improving the DDL capabilities in a way that exceeds capabilities of user management services. + +* `~.ServerUserServices.get_all()` - Returns information about all users. + +* `~.ServerUserServices.get()` - Returns information about specified users. + +* `~.ServerUserServices.add()` - Add new user. + +* `~.ServerUserServices.update()` - Update user information. + +* `~.ServerUserServices.delete()` - Delete user. + +* `~.ServerUserServices.exists()` - Returns True if user exists. + + +## Trace sessions + +!!! important + + Because trace functionality may depend on the version of the Firebird server, this + functionality is made available through a separate class `.ServerTraceServices`. + The `.Server.trace` property provides access to instance of `.ServerTraceServices` or + its **ancestor** class according to attached Firebird server version. + +* `.ServerTraceServices.start()` - Start new trace session. Requires trace `configuration` and returns `Session ID`. + + This method is so-called `Async service` that only starts the trace session. Output + from trace session could be read by one from many methods for [text output from Services](working-with-services.md#text-output-from-services) + that `.Server` provides . + + ```python + from firebird.driver import connect_server + + trace_config = """database = %[\\/]employee.fdb + { + enabled = true + log_statement_finish = true + print_plan = true + include_filter = %%SELECT%% + exclude_filter = %%RDB$%% + time_threshold = 0 + max_sql_length = 2048 + } + """ + + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: + trace_id = srv.trace.start(trace_config,'test_trace_1') + trace_log = [] + # Get first 10 lines of trace output + for i in range(10): + trace_log.append(srv.readline()) + # Stop trace session + # Because trace session blocks the connection, we need another one to stop trace session! + with connect_server('localhost', user='SYSDBA', password='masterkey') as srv_aux: + srv_aux.trace.stop(trace_id) + + ``` + +* `.ServerTraceServices.stop()` - Stop trace session. + +* `.ServerTraceServices.suspend()` - Suspend trace session. + +* `.ServerTraceServices.resume()` - Resume trace session. + +* `.ServerTraceServices.sessions` - Dictionary with active trace sessions. The key is session ID, value is `.TraceSession` instance. diff --git a/docs/zensical.toml b/docs/zensical.toml index d7d91e7..36254e6 100644 --- a/docs/zensical.toml +++ b/docs/zensical.toml @@ -6,7 +6,18 @@ site_url = "https://firebird-driver.readthedocs.io/" nav = [ { "Home" = "index.md" }, { "Getting Started" = "getting-started.md" }, - { "Usage Guide" = "usage-guide.md" }, + { "Usage Guide" = [ + { "Driver structure" = "usage-guide/driver-structure.md" }, + { "Configuration" = "usage-guide/configuration.md" }, + { "Databases" = "usage-guide/databases.md" }, + { "Executing SQL Statements" = "usage-guide/executing-sql-statements.md" }, + { "Data handling and conversions" = "usage-guide/data-handling-and-conversions.md" }, + { "Transanction management" = "usage-guide/transanction-management.md" }, + { "Database Events" = "usage-guide/database-events.md" }, + { "Working with Services" = "usage-guide/working-with-services.md" }, + { "Logging driver activities" = "usage-guide/logging-driver-activities.md" }, + { "Driver hooks" = "usage-guide/driver-hooks.md" }, + ] }, { "Python DB API compliance" = "python-db-api-compliance.md" }, { "Reference" = [ { "Main namespace" = "ref-main.md" }, From fe648379f9b07419d43580dc3684195be6f170f1 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Thu, 8 Oct 2026 17:19:04 +0200 Subject: [PATCH 15/48] Development-related information --- AGENTS.md | 19 ++++++++++++++ README.md | 22 ++-------------- development/README.md | 55 +++++++++++++++++++++++++++++++++++++++ development/__init__.md | 12 +++++++++ development/config.md | 14 ++++++++++ development/core.md | 20 ++++++++++++++ development/fbapi.md | 13 +++++++++ development/hooks.md | 12 +++++++++ development/interfaces.md | 15 +++++++++++ development/types.md | 13 +++++++++ docs/docs/ref-intf.md | 10 +++---- 11 files changed, 180 insertions(+), 25 deletions(-) create mode 100644 AGENTS.md create mode 100644 development/README.md create mode 100644 development/__init__.md create mode 100644 development/config.md create mode 100644 development/core.md create mode 100644 development/fbapi.md create mode 100644 development/hooks.md create mode 100644 development/interfaces.md create mode 100644 development/types.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..a7574c8 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,19 @@ +# Project guidance + +This file applies to the repository root. All paths below are relative to that root. + +- Read [development/README.md](development/README.md) before changing the driver, tests, or build workflow. +- For changes under `src/firebird/driver/`, read the matching module note. Keep module-specific + findings there rather than expanding this file: + [__init__](development/__init__.md), + [config](development/config.md), + [core](development/core.md), + [fbapi](development/fbapi.md), + [hooks](development/hooks.md), + [interfaces](development/interfaces.md), and + [types](development/types.md). +- Keep developer information in `development/`. `docs/docs/` contains the Zensical documentation + for driver users. +- Check `git status` before editing and preserve unrelated work. Verify changes with the focused + tests and build commands described in the development README; report any Firebird-dependent + checks that could not run. diff --git a/README.md b/README.md index 2f57d17..77b48ef 100644 --- a/README.md +++ b/README.md @@ -43,23 +43,5 @@ The documentation for this package is available at [https://firebird-driver.read ## Running tests -This project uses [hatch](https://hatch.pypa.io/latest/) , so you can use: -```console -hatch test -``` -to run all tests for default Python version (3.11). To run tests for all Python versions -defined in matrix, use `-a` switch. - -This project is using [pytest](https://docs.pytest.org/en/stable/) for testing, and our -tests add several options via `tests/conftest.py`. - -By default, tests are configured to use local Firebird installation via network access. -To use local installation in `embedded` mode, comment out the section: -``` -[tool.hatch.envs.hatch-test] -extra-args = ["--host=localhost"] -``` -in `pyproject.toml`. - -You can also use firebird driver configuration file to specify server(s) that should be -used for testing, and then pass `--driver-config` and `--server` options to `pytest`. +See [development/README.md](development/README.md) for the Firebird test setup, Hatch +commands, and development workflow. diff --git a/development/README.md b/development/README.md new file mode 100644 index 0000000..d0f53f0 --- /dev/null +++ b/development/README.md @@ -0,0 +1,55 @@ +# Driver development + +Paths and commands written in prose are relative to the repository root unless a command +explicitly changes directory. Markdown links are relative to this file. This directory contains +developer information. The published user documentation is in `docs/docs/` and is built with Zensical. + +## Package layout + +The Python package is `src/firebird/driver/`. Its public namespace is assembled in `__init__.py`; +the other modules separate configuration, DB API behavior, client library bindings, interface +wrappers, types, and hooks. Read the module note before changing its source: + +| Source module | Development note | Main responsibility | +| --- | --- | --- | +| `__init__.py` | [__init__.md](__init__.md) | Public exports and version | +| `config.py` | [config.md](config.md) | Driver, server, and database configuration | +| `core.py` | [core.md](core.md) | Connections, transactions, cursors, events, and services | +| `fbapi.py` | [fbapi.md](fbapi.md) | `ctypes` bindings and client library loading | +| `hooks.py` | [hooks.md](hooks.md) | Driver hook kinds and registration imports | +| `interfaces.py` | [interfaces.md](interfaces.md) | Firebird object API wrappers | +| `types.py` | [types.md](types.md) | DB API exceptions, constants, flags, and data types | + +The package requires Python 3.11 or newer and depends on `firebird-base` and `python-dateutil`. +`pyproject.toml` is the source of truth for supported test interpreters and build dependencies. + +## Tests + +The tests in `tests/` are integration tests. `tests/conftest.py` loads the Firebird client +API and connects to a Firebird service manager during pytest configuration. It selects a prepared +database for Firebird 3, 4, or 5, copies it into a temporary directory, and configures a `pytest` +database entry. A working client library, server, and matching test database are therefore +needed even for many narrowly selected tests. + +From the repository root, `hatch test` runs the default test environment; `hatch test -a` +runs its Python 3.11–3.14 matrix. The `hatch-test` environment in `pyproject.toml` passes +`--host=localhost` by default. `tests/conftest.py` also accepts `--host`, `--port`, `--client-lib`, +`--driver-config`, and `--server`. Use a focused test file while developing, then run the +wider suite when the prepared Firebird environment is available. Do not treat a missing server +or client library as a passing test. + +For embedded-mode testing, remove the `--host=localhost` extra argument from `[tool.hatch.envs.hatch-test]` +in `pyproject.toml` and provide a suitable local client library. Alternatively, use a driver +configuration file with `--driver-config` and select a named server with `--server`. Check +`tests/conftest.py` for how these options are applied before the API is loaded. + +## Documentation and packaging + +From the repository root, `hatch run doc:build` builds `docs/zensical.toml` and the Markdown +pages in `docs/docs/`. `hatch run doc:serve` previews them. `hatch run doc:docset` builds +a Dash/Zeal docset and archives it in `dist/`. Read the Docs uses `.readthedocs.yml` to +publish the Zensical output. Keep user-facing API descriptions in source docstrings and +`docs/docs/`; keep implementation and test guidance here. + +The project builds with Hatchling. The version comes from `src/firebird/driver/__init__.py`, +and Ruff settings are in `pyproject.toml`. diff --git a/development/__init__.md b/development/__init__.md new file mode 100644 index 0000000..042e559 --- /dev/null +++ b/development/__init__.md @@ -0,0 +1,12 @@ +# `firebird.driver.__init__` + +Source: `src/firebird/driver/__init__.py`, relative to the repository root. + +This module re-exports the public DB API, configuration objects, hook access points, and +selected types from the implementation modules. It also defines `__VERSION__`, which Hatchling +reads for the package version and the docset script reads for its archive name. + +When changing a public symbol, check whether it must be exported here and documented in +`docs/docs/ref-main.md` or another API page. Keep implementations in their owning modules. +Check imports after export changes because importing `firebird.driver` loads several +implementation modules and registers API hooks. diff --git a/development/config.md b/development/config.md new file mode 100644 index 0000000..adb3bcf --- /dev/null +++ b/development/config.md @@ -0,0 +1,14 @@ +# `firebird.driver.config` + +Source: `src/firebird/driver/config.py`, relative to the repository root. + +`ServerConfig` and `DatabaseConfig` define connection settings. `DriverConfig` holds global +settings, server and database defaults, and named registration lists. The module-level +`driver_config` is the shared configuration object. Configuration loading uses the `firebird.base.config` +parser with environment interpolation; registration rejects duplicate names. + +Set `driver_config.fb_client_library.value` before the first call that loads the Firebird API. +`fbapi.get_api()` caches that API, so changing the configured path afterward does not reload +the library. Changes to defaults, named entries, or connection option precedence should be +checked against `tests/test_connection.py`, `tests/test_server.py`, and the configuration +setup in `tests/conftest.py`. diff --git a/development/core.md b/development/core.md new file mode 100644 index 0000000..43709cf --- /dev/null +++ b/development/core.md @@ -0,0 +1,20 @@ +# `firebird.driver.core` + +Source: `src/firebird/driver/core.py`, relative to the repository root. + +This module implements the high-level DB API: `connect()`, `create_database()`, `connect_server()`, +`Connection`, `TransactionManager`, `Cursor`, statements, BLOB handling, database events, +and service manager operations. It also builds parameter buffers and exposes version-sensitive +information providers. + +Keep resource ownership aligned with this structure. A `Connection` owns its transaction managers, +statements, and event collectors; each `Cursor` holds its own transaction manager reference. +The connection creates a main transaction, a read-only query transaction, and an internal cursor. +Closing a connection must account for its dependent resources. The `transaction()` context +manager begins a transaction and commits or rolls back on exit; with `bypass=True`, it joins +an already active transaction without finishing it. + +For changes here, select tests by behavior: `test_connection.py`, `test_transaction.py`, +`test_cursor.py`, `test_statement.py`, `test_blob.py`, `test_array.py`, `test_events.py`, +`test_distributed_trans.py`, `test_server.py`, and `test_info_providers.py`. Exercise the real +prepared Firebird environment for lifecycle and wire protocol changes. diff --git a/development/fbapi.md b/development/fbapi.md new file mode 100644 index 0000000..4f1b039 --- /dev/null +++ b/development/fbapi.md @@ -0,0 +1,13 @@ +# `firebird.driver.fbapi` + +Source: `src/firebird/driver/fbapi.py`, relative to the repository root. + +This is the low-level `ctypes` boundary. It defines Firebird C constants, structures, vtables, +and the `FirebirdAPI` loader. `get_api()` calls `load_api()` on first use; the loaded API +is cached in the module. An explicit filename or `driver_config.fb_client_library.value` +selects the client library before first load. The `APIHook.LOADED` callbacks run after initialization. + +Changes to C layouts, pointer types, or signatures can affect every higher-level wrapper. +Compare them with the supported Firebird client API and run focused integration tests on +the affected Firebird versions. Preserve the initialization order used by `interfaces.py` +and `core.py` hooks. diff --git a/development/hooks.md b/development/hooks.md new file mode 100644 index 0000000..8f3a080 --- /dev/null +++ b/development/hooks.md @@ -0,0 +1,12 @@ +# `firebird.driver.hooks` + +Source: `src/firebird/driver/hooks.py`, relative to the repository root. + +The module defines `APIHook`, `ConnectionHook`, and `ServerHook` event kinds and exposes +registration helpers from `firebird.base.hooks`. `fbapi.py`, `interfaces.py`, and `core.py` +register or invoke these hooks during API loading, attachment, detachment, and service connection. + +When adding or changing an event, trace both registration and invocation sites, including +callback arguments and whether a return value can alter the operation. `tests/test_hooks.py` +covers hook ordering and connection lifecycle behavior. Clear global hook registrations between +tests that mutate them. diff --git a/development/interfaces.md b/development/interfaces.md new file mode 100644 index 0000000..0a047f1 --- /dev/null +++ b/development/interfaces.md @@ -0,0 +1,15 @@ +# `firebird.driver.interfaces` + +Source: `src/firebird/driver/interfaces.py`, relative to the repository root. + +This module wraps Firebird's object API interfaces over the `ctypes` declarations in `fbapi.py`. +The `iVersionedMeta` constructor selects a wrapper class based on the returned interface +version. Versioned classes such as `iAttachment_v3` and `iAttachment_v4` preserve behavior +for older engines; the canonical wrapper represents the newest supported interface. + +Ownership matters at this boundary: reference-counted wrappers release references, and +disposable wrappers dispose their interfaces. Status checking translates Firebird status +vectors into driver errors or warnings. On `APIHook.LOADED`, the module obtains the master +and utility interfaces and attaches them to the API object. Check wrapper changes against +the matching `fbapi.py` declarations and run integration tests for the Firebird versions +they affect. diff --git a/development/types.md b/development/types.md new file mode 100644 index 0000000..9a293b1 --- /dev/null +++ b/development/types.md @@ -0,0 +1,13 @@ +# `firebird.driver.types` + +Source: `src/firebird/driver/types.py`, relative to the repository root. + +This module defines DB API exception classes, Firebird protocol and information codes, +parameter block items, flags, dataclasses, and typing helpers. It also defines the DB API +constants `apilevel`, `threadsafety`, and `paramstyle`, plus date/time constructors and +type objects. Public selections are re-exported by `__init__.py`. + +Keep numeric protocol values and flag combinations consistent with the Firebird client API. +If a type or exception changes, check its use in `core.py` and `interfaces.py` and the relevant +DB API compliance and information provider tests. Do not change exception inheritance or +public constants without checking their DB API contract. diff --git a/docs/docs/ref-intf.md b/docs/docs/ref-intf.md index 7fb9430..6834a57 100644 --- a/docs/docs/ref-intf.md +++ b/docs/docs/ref-intf.md @@ -18,7 +18,7 @@ This module contains interface wrappers for Firebird new API. In Python driver, interfaces are represented as instances of interface wrapper classes that expose the methods provided by particular Firebird interface version. The wrapper -class hierarchy thus represent not only inheritabce between Firebird interfaces, but also +class hierarchy thus represent not only inheritance between Firebird interfaces, but also between versions of particular Firebird interface. Because all interfaces returned by Firebird are inherited from `IVersioned` interface, @@ -26,7 +26,7 @@ all wrapper classes have `VERSION` class attribute that contain version number o interface. Each Firebird interface has it's "canonical" Python wrapper with coresponding name. For -example interface `IService` has wrapper class `.iService`. However, if there are multiple +example interface `IService` has wrapper class `iService`. However, if there are multiple public versions of Firebird interface, there are multiple wrapper classes for each published interface version (interim, non-public versions used during Firebird development are skipped). These wrapper classes have names based on their canonical name with suffix that represent @@ -40,9 +40,9 @@ that correct wrapper class is used according to returned interface version. However, this architecture has several important consequences: 1. The interface wrapper classes may change between driver releases as new interface versions - are introduced. For example, driver versions up to 1.5.2 had only canonical `.iService` - (version 3), but in version 1.6.0 it was renamed to `.iService_v3`, new wrappers - `.iService_v4` and (new canonical) `.iService` (version 5) were added. + are introduced. For example, driver versions up to 1.5.2 had only canonical `iService` + (version 3), but in version 1.6.0 it was renamed to `iService_v3`, new wrappers + `iService_v4` and (new canonical) `iService` (version 5) were added. 2. Instead using `isinstance` to check interface versions, you should always use `VERSION` attribute on wrapper class instance. From eef5b1aa3987523cf9879def9fe76bdcec4ad75d Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Thu, 8 Oct 2026 19:56:19 +0200 Subject: [PATCH 16/48] Documentation fixes and improvements --- CHANGELOG.md | 8 +- docs/docs/getting-started.md | 9 +- docs/docs/python-db-api-compliance.md | 131 ++++++------- docs/docs/ref-core.md | 16 +- docs/docs/ref-hooks.md | 6 +- docs/docs/ref-main.md | 15 +- docs/docs/ref-types.md | 9 +- docs/docs/usage-guide/configuration.md | 12 +- .../data-handling-and-conversions.md | 33 ++-- docs/docs/usage-guide/database-events.md | 27 ++- docs/docs/usage-guide/databases.md | 100 +++++----- docs/docs/usage-guide/driver-hooks.md | 22 +-- docs/docs/usage-guide/driver-structure.md | 18 +- .../usage-guide/executing-sql-statements.md | 120 ++++++------ .../usage-guide/logging-driver-activities.md | 134 +++++-------- ...sanction-management.md => transactions.md} | 141 +++++++------- .../docs/usage-guide/working-with-services.md | 184 +++++++++--------- docs/zensical.toml | 2 +- 18 files changed, 474 insertions(+), 513 deletions(-) rename docs/docs/usage-guide/{transanction-management.md => transactions.md} (65%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c1192a..51640ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -247,7 +247,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed - `firebird.driver.core.create_database()` now use server configuration user/password - if either is not specified in database configuration (like `.connect()`) + if either is not specified in database configuration (like [`connect()`](https://firebird-driver.readthedocs.io/en/latest/ref-core/#firebird.driver.core.connect)) - Problem in `Server` processing incomplete LINE responses. ### Changed @@ -318,7 +318,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - `tpb` parameter `access` renamed to `access_mode`. - `FirebirdWarning` now descends from `UserWarning` instead `Warning`, and is reported - to application via `.warnings.warn` instead raised as exception. + to application via [`warnings.warn`](https://docs.python.org/3/library/warnings.html#warnings.warn) instead raised as exception. - `iAttachment_v3` attribute `charset` was renamed to `encoding`. - `iXpbBuilder.insert_string` optional parameter `encoding` is now keyword-only. Parameter also added to `iXpbBuilder.get_string` method. @@ -415,7 +415,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed - Bug GH-4: exeption returns non ascii-127 symbols. - The error message decode uses `.fbapi.err_encoding` value that is initialized to + The error message decode uses [`fbapi.err_encoding`](https://firebird-driver.readthedocs.io/en/latest/ref-fbapi/#firebird.driver.fbapi.err_encoding) value that is initialized to `locale.getpreferredencoding`. Also, the decode is now done with `errors="replace"`. - Unregistered bug: wrong handling of milliseconds in TIME and TEMEPSTAMP datatype. - Sync `_VERSION_` value with package version @@ -517,7 +517,7 @@ for Firebird 4 is still evolving till final release). - Interface wrapper moved to separate module - Buffer managers moved to `firebird.driver.core` module -- Module `~firebird.driver.core`: +- Module [`firebird.driver.core`](https://firebird-driver.readthedocs.io/en/latest/ref-core/): - `connect()`, `create_database()` and `connect_server()` now use driver configuration. - Simplified/unified transaction isolation specification. diff --git a/docs/docs/getting-started.md b/docs/docs/getting-started.md index fba6f7b..41fd67f 100644 --- a/docs/docs/getting-started.md +++ b/docs/docs/getting-started.md @@ -42,6 +42,11 @@ strings (in `.ini-style` `ConfigParser` format). ## Connecting to a Database +The examples use `employee`, the local alias for the Firebird sample database included +with each Firebird installation. The driver builds a connection DSN from this alias +and the current settings. For your own databases, define server and database settings +as described in [Server and database configuration](usage-guide/configuration.md#server-and-database-configuration). + **Example 1:** A simple database connection is typically established with code such as this: @@ -102,8 +107,8 @@ con = connect('employee') ## Creating a Database -A database is created using `~firebird.driver.core.create_database()` function. -Like `~firebird.driver.core.connect()`, this function uses configuration for specification of +A database is created using [`create_database()`](ref-core.md#firebird.driver.core.create_database) function. +Like [`connect()`](ref-core.md#firebird.driver.core.connect), this function uses configuration for specification of database parameters like page size, sweep interval etc. ## Executing SQL Statements diff --git a/docs/docs/python-db-api-compliance.md b/docs/docs/python-db-api-compliance.md index 2c1ec03..7cba790 100644 --- a/docs/docs/python-db-api-compliance.md +++ b/docs/docs/python-db-api-compliance.md @@ -24,22 +24,22 @@ Full text of Python Database API 2.0 (PEP 249) is available at ## Nominally Supported Optional Features -`.Cursor` +### Cursor - `~.Cursor.arraysize` +[`Cursor.arraysize`](ref-core.md#firebird.driver.core.Cursor) - As required by the spec, the value of this attribute is observed with - respect to the `fetchmany` method. However, changing the value of this - attribute does not make any difference in fetch efficiency because - the database engine only supports fetching a single row at a time. +As required by the spec, the value of this attribute is observed with +respect to the `fetchmany` method. However, changing the value of this +attribute does not make any difference in fetch efficiency because +the database engine only supports fetching a single row at a time. - `~.Cursor.setinputsizes` +[`Cursor.setinputsizes`](ref-core.md#firebird.driver.core.Cursor.setinputsizes) - Although this method is present, it does nothing, as allowed by the spec. +Although this method is present, it does nothing, as allowed by the spec. - `~.Cursor.setoutputsize` +[`Cursor.setoutputsize`](ref-core.md#firebird.driver.core.Cursor.setoutputsize) - Although this method is present, it does nothing, as allowed by the spec. +Although this method is present, it does nothing, as allowed by the spec. ## Caveats @@ -49,76 +49,73 @@ of the Python DB API. This section attempts to document only those features that overlap with the DB API. -`.Connection` +### Connection - `~.Connection.commit(retaining=False)` - `~.Connection.rollback(retaining=False, savepoint=None)` +`Connection.commit(retaining=False)` and +`Connection.rollback(retaining=False, savepoint=None)` accept an optional boolean +`retaining` parameter. It determines whether the transaction context is recycled; +see [Retaining transactions](usage-guide/transactions.md#retaining-transactions). - The `commit` and `rollback` methods accept an optional boolean parameter `retaining` - (default `False`) that indicates whether the transactional context of the transaction - being resolved should be recycled. For details, see the Advanced - Transaction Control: Retaining Operations section of this document. - The `rollback` method accepts an optional string parameter `savepoint` - that causes the transaction to roll back only as far as the designated - savepoint, rather than rolling back entirely. For details, see the - Advanced Transaction Control: Savepoints section of this document. +`Connection.rollback()` also accepts an optional `savepoint` name. This rolls back +to the named savepoint rather than ending the entire transaction; see +[Savepoints](usage-guide/transactions.md#savepoints). -`.Cursor` +### Cursor - `~.Cursor.description` +[`Cursor.description`](ref-core.md#firebird.driver.core.Cursor.description) - Firebird-driver makes absolutely no guarantees about `description` except those - required by the Python Database API Specification 2.0 (that is, `description` - is either `None` or a sequence of 7-element sequences). Therefore, client - programmers should *not* rely on `description` being an instance of a particular - class or type. Firebird-driver provides several named positional constants to be - used as indices into a given element of `description` . The contents - of all `description` elements are defined by the DB API spec; these - constants are provided merely for convenience. +Firebird-driver makes absolutely no guarantees about `description` except those +required by the Python Database API Specification 2.0 (that is, `description` +is either `None` or a sequence of 7-element sequences). Therefore, client +programmers should *not* rely on `description` being an instance of a particular +class or type. Firebird-driver provides several named positional constants to be +used as indices into a given element of `description`. The contents +of all `description` elements are defined by the DB API spec; these +constants are provided merely for convenience. - ```python - DESCRIPTION_NAME - DESCRIPTION_TYPE_CODE - DESCRIPTION_DISPLAY_SIZE - DESCRIPTION_INTERNAL_SIZE - DESCRIPTION_PRECISION - DESCRIPTION_SCALE - DESCRIPTION_NULL_OK +```python +DESCRIPTION_NAME +DESCRIPTION_TYPE_CODE +DESCRIPTION_DISPLAY_SIZE +DESCRIPTION_INTERNAL_SIZE +DESCRIPTION_PRECISION +DESCRIPTION_SCALE +DESCRIPTION_NULL_OK - ``` +``` - Here is an example of accessing the *name* of the first field in the - `description` of cursor `cur`: +Here is an example of accessing the *name* of the first field in the +`description` of cursor `cur`: - ```python - nameOfFirstField = cur.description[0][firebird.driver.DESCRIPTION_NAME] +```python +nameOfFirstField = cur.description[0][firebird.driver.DESCRIPTION_NAME] - ``` +``` - For more information, see the documentation of Cursor.description in - the [DB API Specification](https://peps.python.org/pep-0249/). +For more information, see the documentation of Cursor.description in +the [DB API Specification](https://peps.python.org/pep-0249/). - `~.Cursor.rowcount` +[`Cursor.rowcount`](ref-core.md#firebird.driver.core.Cursor) - Although `Cursor` in Firebird-driver implement this attribute, - the database engine's own support for the determination of - "rows affected"/"rows selected" is quirky. The database engine only - supports the determination of rowcount for `INSERT`, `UPDATE`, - `DELETE`, and `SELECT` statements. When stored procedures become - involved, row count figures are usually not available to the client. - Determining rowcount for `SELECT` statements is problematic: the - rowcount is reported as zero until at least one row has been fetched - from the result set, and the rowcount is misreported if the result set - is larger than 1302 rows. The server apparently marshals result sets - internally in batches of 1302, and will misreport the rowcount for - result sets larger than 1302 rows until the 1303rd row is fetched, - result sets larger than 2604 rows until the 2605th row is fetched, and - so on, in increments of 1302. As required by the Python DB API Spec, - the rowcount attribute "is -1 in case no executeXX() has been - performed on the cursor or the rowcount of the last operation is not - determinable by the interface". +Although `Cursor` in Firebird-driver implements this attribute, +the database engine's own support for the determination of +"rows affected"/"rows selected" is quirky. The database engine only +supports the determination of rowcount for `INSERT`, `UPDATE`, +`DELETE`, and `SELECT` statements. When stored procedures become +involved, row count figures are usually not available to the client. +Determining rowcount for `SELECT` statements is problematic: the +rowcount is reported as zero until at least one row has been fetched +from the result set, and the rowcount is misreported if the result set +is larger than 1302 rows. The server apparently marshals result sets +internally in batches of 1302, and will misreport the rowcount for +result sets larger than 1302 rows until the 1303rd row is fetched, +result sets larger than 2604 rows until the 2605th row is fetched, and +so on, in increments of 1302. As required by the Python DB API Spec, +the rowcount attribute "is -1 in case no executeXX() has been +performed on the cursor or the rowcount of the last operation is not +determinable by the interface". - !!! note +!!! note - This attribute is just an alias for `.Cursor.affected_rows` property. + This attribute is just an alias for the [`Cursor.affected_rows`](ref-core.md#firebird.driver.core.Cursor.affected_rows) property. diff --git a/docs/docs/ref-core.md b/docs/docs/ref-core.md index 0a5f53a..b6ce529 100644 --- a/docs/docs/ref-core.md +++ b/docs/docs/ref-core.md @@ -7,14 +7,14 @@ This is the main code module of the Firebird driver. ### C integer limit constants - - SHRT_MIN - - SHRT_MAX - - USHRT_MAX - - INT_MIN - - INT_MAX - - UINT_MAX - - LONG_MIN - - LONG_MAX +- SHRT_MIN +- SHRT_MAX +- USHRT_MAX +- INT_MIN +- INT_MAX +- UINT_MAX +- LONG_MIN +- LONG_MAX ### Translation dictionaries diff --git a/docs/docs/ref-hooks.md b/docs/docs/ref-hooks.md index af9c709..6e4a817 100644 --- a/docs/docs/ref-hooks.md +++ b/docs/docs/ref-hooks.md @@ -3,9 +3,9 @@ This module contains firebird-driver hooks. Uses hook mechanism from firebird-base package. -Imports from `firebird.base.hooks`: `~firebird.base.hooks.register_class`, -`~firebird.base.hooks.get_callbacks`, `~firebird.base.hooks.add_hook` and -`~firebird.base.hooks.hook_manager`. +Imports from `firebird.base.hooks`: [`register_class`](https://firebird-base.readthedocs.io/en/latest/hooks/#firebird.base.hooks.register_class), +[`get_callbacks`](https://firebird-base.readthedocs.io/en/latest/hooks/#firebird.base.hooks.get_callbacks), [`add_hook`](https://firebird-base.readthedocs.io/en/latest/hooks/#firebird.base.hooks.add_hook) and +[`hook_manager`](https://firebird-base.readthedocs.io/en/latest/hooks/#firebird.base.hooks.hook_manager). ## Enums diff --git a/docs/docs/ref-main.md b/docs/docs/ref-main.md index db108b0..e0af2b7 100644 --- a/docs/docs/ref-main.md +++ b/docs/docs/ref-main.md @@ -9,6 +9,7 @@ ### config +Classes: `DatabaseConfig`, `DriverConfig`, and `ServerConfig`. Globals: `driver_config` @@ -16,34 +17,34 @@ Globals: `driver_config` Functions: - `connect()`, `create_database()`, `connect_server()`, `transaction()` and `tpb()` + `connect()`, `create_database()`, `connect_server()`, `temp_database()`, `transaction()` and `tpb()` Translation dictionaries: `CHARSET_MAP` +Sentinels: + `TIMEOUT` + Classes: - `DistributedTransactionManager`, `Connection`, `Cursor`, `Server` and `TPB` + `Connection`, `Cursor`, `Server`, `Statement`, `TransactionManager`, `DistributedTransactionManager` and `TPB` ### types Exceptions: - `Warning`, `Error`, `InterfaceError`, `DatabaseError`, `DataError`, + `FirebirdWarning`, `Error`, `InterfaceError`, `DatabaseError`, `DataError`, `OperationalError`, `IntegrityError`, `InternalError`, `ProgrammingError` and `NotSupportedError` Enums: `NetProtocol`, `DirectoryCode`, `PageSize`, `DBKeyScope`, `DbInfoCode`, `Features`, - `TraInfoCode`, `ReplicaMode`, `StmtInfoCode`, `TraInfoIsolation`, + `TraInfoCode`, `ReplicaMode`, `StmtInfoCode`, `ResultSetInfoCode`, `SrvInfoCode`, `TraInfoIsolation`, `TraInfoReadCommitted`, `TraInfoAccess`, `TraIsolation`, `TraReadCommitted`, `TraLockResolution`, `TraAccessMode`, `TableShareMode`, `TableAccessMode`, `Isolation`, `DefaultAction`, `StatementType`, `BlobType`, `DbAccessMode`, `DbSpaceReservation`, `DbWriteMode`, `ShutdownMode`, `OnlineMode`, `ShutdownMethod`, `CancelType`, `DecfloatRound` and `DecfloatTraps` -Sentinels: - `~firebird.driver.core.TIMEOUT` - Flags: `ServerCapability`, `SrvRepairFlag`, `SrvStatFlag`, `SrvBackupFlag`, `SrvRestoreFlag`, `SrvNBackupFlag`, `ConnectionFlag` and `EncryptionFlag` diff --git a/docs/docs/ref-types.md b/docs/docs/ref-types.md index 065c557..1396be2 100644 --- a/docs/docs/ref-types.md +++ b/docs/docs/ref-types.md @@ -30,9 +30,7 @@ Next exceptions are required by Python DB API 2.0 This is the exception inheritance layout: ```text -StandardError -|__UserWarning - |__FirebirdWarning +Exception |__Error |__InterfaceError |__DatabaseError @@ -43,6 +41,9 @@ StandardError |__ProgrammingError |__NotSupportedError +UserWarning +|__FirebirdWarning + ``` ## Other constants and types required by Python DB API 2.0 specification @@ -54,7 +55,7 @@ StandardError ::: firebird.driver.types.paramstyle -### Helper constants for work with `.Cursor.description` content +### Helper constants for work with [`Cursor.description`](ref-core.md#firebird.driver.core.Cursor.description) content - DESCRIPTION_NAME - DESCRIPTION_TYPE_CODE diff --git a/docs/docs/usage-guide/configuration.md b/docs/docs/usage-guide/configuration.md index a6c0b08..4fb676a 100644 --- a/docs/docs/usage-guide/configuration.md +++ b/docs/docs/usage-guide/configuration.md @@ -13,7 +13,7 @@ strings (in `.ini-style` `configparser` format). ## The 'driver_config' object -The global `.driver_config` object holds all configurable driver parameters, and access +The global [`driver_config`](../ref-config.md#firebird.driver.config.driver_config) object holds all configurable driver parameters, and access configuration parameters for registered Firebird servers and databases. In initial state, all parameters have default values and there are no registered servers @@ -24,13 +24,13 @@ configuration string, dict or file(s). !!! important If you want to use specific Firebird client library, you must set the value of - `.DriverConfig.fb_client_library` configuration option **before** your application - calls any from following functions: `.connect()`, `~firebird.driver.core.create_database()`, - `.connect_server()`, `.load_api()` or `.get_api()`. + [`DriverConfig.fb_client_library`](../ref-config.md#firebird.driver.config.DriverConfig) configuration option **before** your application + calls any from following functions: [`connect()`](../ref-core.md#firebird.driver.core.connect), [`create_database()`](../ref-core.md#firebird.driver.core.create_database), + [`connect_server()`](../ref-core.md#firebird.driver.core.connect_server), [`load_api()`](../ref-fbapi.md#firebird.driver.fbapi.load_api) or [`get_api()`](../ref-fbapi.md#firebird.driver.fbapi.get_api). !!! info - `.DriverConfig` for list of available methods and parameters. + [`DriverConfig`](../ref-config.md#firebird.driver.config.DriverConfig) for list of available methods and parameters. ## Server and database configuration @@ -54,4 +54,4 @@ or configuration, and few keyword parameters to specify / override selected opti !!! info - `.ServerConfig` and `.DatabaseConfig` for list of available methods and parameters. + [`ServerConfig`](../ref-config.md#firebird.driver.config.ServerConfig) and [`DatabaseConfig`](../ref-config.md#firebird.driver.config.DatabaseConfig) for list of available methods and parameters. diff --git a/docs/docs/usage-guide/data-handling-and-conversions.md b/docs/docs/usage-guide/data-handling-and-conversions.md index 267421c..1d61021 100644 --- a/docs/docs/usage-guide/data-handling-and-conversions.md +++ b/docs/docs/usage-guide/data-handling-and-conversions.md @@ -88,8 +88,8 @@ including automatic transliteration between character sets when necessary. especially when database operates with multiple character sets, or uses character set that is not `native` for client application. - Character set for communication is specified using `~.DatabaseConfig.charset` - configuration option, or parameter in `.connect()` or `~firebird.driver.core.create_database()` call. + Character set for communication is specified using [`charset`](../ref-config.md#firebird.driver.config.DatabaseConfig) + configuration option, or parameter in [`connect()`](../ref-core.md#firebird.driver.core.connect) or [`create_database()`](../ref-core.md#firebird.driver.core.create_database) call. When `connection charset` is defined, all textual data returned from server are encoded in this charset, and client application must ensure that all textual data sent to server @@ -129,8 +129,6 @@ determine encoding for conversions from/to `unicode`. make your life much easier. - - ## Working with TIME/TIMESTAMP WITH TIMEZONE Firebird 4 introduced support for TIME and TIMESTAMP WITH TIMEZONE. The driver supports these @@ -141,11 +139,12 @@ support has some specific limitations: requirements it's not possible to use standard `zoneinfo` package available in Python since version 3.9, neither any other `datetime.tzinfo` implementation. 2. All timezone-aware `datetime.datetime` and `datetime.time` objects passed to the driver - must use `datetime.tzinfo` created with `.get_timezone()` utility function. + must use `datetime.tzinfo` created with [`get_timezone()`](../ref-types.md#firebird.driver.types.get_timezone) utility function. **Examples:** ```python +import datetime from firebird.driver import get_timezone ts_region = datetime.datetime(2020, 12, 31, 23, 55, 35, 123400, get_timezone('Europe/Prague')) @@ -153,6 +152,8 @@ ts_offset = datetime.datetime(2020, 12, 31, 23, 55, 35, 123400, get_timezone('+0 ``` + + ## Working with BLOBs Firebird-driver uses two types of BLOB values: @@ -171,16 +172,16 @@ These drawbacks are addressed by `stream` BLOBs. Using BLOBs in `stream` mode is * For **input** values, simply use [parameterized statement](executing-sql-statements.md#parameterized-statements) and pass any `file-like` object in place of BLOB parameter. The `file-like` object must - implement only the `~file.read` method, as no other method is used. + implement only the [`read`](https://docs.python.org/3/library/io.html#io.IOBase) method, as no other method is used. * For **output** values, add column name(s) that should be returned as `file-like` - objects to `.Cursor.stream_blobs` list attribute. Firebird-driver then returns - `.BlobReader` instance instead string in place of returned BLOB value for these column(s). + objects to [`Cursor.stream_blobs`](../ref-core.md#firebird.driver.core.Cursor) list attribute. Firebird-driver then returns + [`BlobReader`](../ref-core.md#firebird.driver.core.BlobReader) instance instead string in place of returned BLOB value for these column(s). !!! important - The firebird-driver provides `.Cursor.stream_blob_threshold` attribute that controls + The firebird-driver provides [`Cursor.stream_blob_threshold`](../ref-core.md#firebird.driver.core.Cursor) attribute that controls the maximum size of materialized blobs (as memory exhaustion safeguard). When particular - blob value exceeds this threshold, an instance of `.BlobReader` is returned instead + blob value exceeds this threshold, an instance of [`BlobReader`](../ref-core.md#firebird.driver.core.BlobReader) is returned instead string/bytes value. Zero threshold value effectively forces all blobs to be returned as stream blobs. @@ -188,15 +189,15 @@ These drawbacks are addressed by `stream` BLOBs. Using BLOBs in `stream` mode is Please note that positive threshold value means that your application has to be prepared to handle BLOBs in both incarnations. - The default threshold is 64K and could be changed using `.DriverConfig.stream_blob_threshold` + The default threshold is 64K and could be changed using [`DriverConfig.stream_blob_threshold`](../ref-config.md#firebird.driver.config.DriverConfig) configuration option. Blob size threshold has effect only on materialized blob columns, i.e. columns not - explicitly requested to be returned as streamed ones using `.Cursor.stream_blobs` + explicitly requested to be returned as streamed ones using [`Cursor.stream_blobs`](../ref-core.md#firebird.driver.core.Cursor) attribute, that are **always** returned as stream blobs. -The `.BlobReader` instance is bound to `.Cursor` instance, and it's automatically closed -with cursor. However, it's good practice to use `with` statement or call `.BlobReader.close()` +The [`BlobReader`](../ref-core.md#firebird.driver.core.BlobReader) instance is bound to [`Cursor`](../ref-core.md#firebird.driver.core.Cursor) instance, and it's automatically closed +with cursor. However, it's good practice to use `with` statement or call [`BlobReader.close()`](../ref-core.md#firebird.driver.core.BlobReader.close) once you're finished reading to release system resources associated with BLOB value. !!! important @@ -204,7 +205,7 @@ once you're finished reading to release system resources associated with BLOB va When working with BLOB values, always have memory efficiency in mind, especially when you're processing huge quantity of rows with BLOB values at once. Materialized BLOB values may exhaust your memory quickly, but using stream BLOBs may have inpact on - performance too, as new `.BlobReader` instance is created for each value fetched. + performance too, as new [`BlobReader`](../ref-core.md#firebird.driver.core.BlobReader) instance is created for each value fetched. **Example program:** @@ -306,7 +307,7 @@ with connect('/temp/test.db', user='sysdba', password='pass') as con: cur.execute("select a from array_table") arrayOut = cur.fetchone()[0] - print(f"{arrayOut=}) + print(f"{arrayOut=}") ``` diff --git a/docs/docs/usage-guide/database-events.md b/docs/docs/usage-guide/database-events.md index d518acd..2488b0b 100644 --- a/docs/docs/usage-guide/database-events.md +++ b/docs/docs/usage-guide/database-events.md @@ -97,13 +97,12 @@ in vain for new messages when there are none available. !!! note If you don't care about the gory details of event notification, - skip to the section that describes FDB's Python-level event handling - API. + skip to the [Python event API](#api-for-python-developers). The Firebird C client library offers two forms of event notification. The first form is *synchronous* notification, by way of the function `isc_wait_for_event()`. This form is admirably simple for a C programmer - to use, but is inappropriate as a basis for FDB's event support, + to use, but is inappropriate as a basis for firebird-driver's event support, chiefly because it's not sophisticated enough to serve as the basis for a comfortable Python-level API. The other form of event notification offered by the database client library is *asynchronous*, by way of the @@ -133,32 +132,32 @@ in vain for new messages when there are none available. ## API for Python developers The Firebird-driver database event API is comprised of the following: the method -`.Connection.event_collector()` and the class `.EventCollector`. +[`Connection.event_collector()`](../ref-core.md#firebird.driver.core.Connection.event_collector) and the class [`EventCollector`](../ref-core.md#firebird.driver.core.EventCollector). -Use the `.Connection.event_collector()` method (takes a sequence of string event -names as parameter) to create `.EventCollector` instance, that collects database event +Use the [`Connection.event_collector()`](../ref-core.md#firebird.driver.core.Connection.event_collector) method (takes a sequence of string event +names as parameter) to create [`EventCollector`](../ref-core.md#firebird.driver.core.EventCollector) instance, that collects database event notifications sent from the server for given database. !!! important - To start listening for events it's necessary to call `.EventCollector.begin()` + To start listening for events it's necessary to call [`EventCollector.begin()`](../ref-core.md#firebird.driver.core.EventCollector.begin) method or use EventCollector's context manager interface. -Immediately when `~.EventCollector.begin()` method is called, EventCollector starts +Immediately when [`begin()`](../ref-core.md#firebird.driver.core.EventCollector.begin) method is called, EventCollector starts to accumulate notifications of any event that occur within the collector’s internal queue -until the collector is closed either explicitly (via the `~.EventCollector.close()` +until the collector is closed either explicitly (via the [`close()`](../ref-core.md#firebird.driver.core.EventCollector.close) method) or implicitly (via garbage collection). -Notifications about events are aquired through call to `~.EventCollector.wait()` method, +Notifications about events are aquired through call to [`wait()`](../ref-core.md#firebird.driver.core.EventCollector.wait) method, that blocks the calling thread until at least one of the events occurs, or the specified `timeout` (if any) expires, and returns `None` if the wait timed out, or a dictionary that maps `event_name -> event_occurrence_count`. !!! important - `.EventCollector` can act as context manager that ensures execution of - `~.EventCollector.begin()` and `~.EventCollector.close()` methods. - It's strongly advised to use the `.EventCollector` with the `with` statement. + [`EventCollector`](../ref-core.md#firebird.driver.core.EventCollector) can act as context manager that ensures execution of + [`begin()`](../ref-core.md#firebird.driver.core.EventCollector.begin) and [`close()`](../ref-core.md#firebird.driver.core.EventCollector.close) methods. + It's strongly advised to use the [`EventCollector`](../ref-core.md#firebird.driver.core.EventCollector) with the `with` statement. **Example:** @@ -170,7 +169,7 @@ with connection.event_collector(['event_a', 'event_b']) as collector: ``` If you want to drop notifications accumulated so far by conduit, call -`.EventCollector.flush()` method. +[`EventCollector.flush()`](../ref-core.md#firebird.driver.core.EventCollector.flush) method. **Example program:** diff --git a/docs/docs/usage-guide/databases.md b/docs/docs/usage-guide/databases.md index 91d2ef3..87a49c4 100644 --- a/docs/docs/usage-guide/databases.md +++ b/docs/docs/usage-guide/databases.md @@ -1,10 +1,10 @@ # Databases -Access to the database is made available through `.Connection` objects. Firebird-driver +Access to the database is made available through [`Connection`](../ref-core.md#firebird.driver.core.Connection) objects. Firebird-driver provides two constructors for these: -* `.connect` - Returns `.Connection` to database that already exists. -* `~firebird.driver.core.create_database` - Returns `.Connection` to newly created database. +* [`connect`](../ref-core.md#firebird.driver.core.connect) - Returns [`Connection`](../ref-core.md#firebird.driver.core.Connection) to database that already exists. +* [`create_database`](../ref-core.md#firebird.driver.core.create_database) - Returns [`Connection`](../ref-core.md#firebird.driver.core.Connection) to newly created database. @@ -26,7 +26,7 @@ options that are not configurable. !!! note If `database` value is not recognized as name of registered database configuration, - the driver uses `~.DriverConfig.db_defaults` and `~.DriverConfig.server_defaults` + the driver uses [`db_defaults`](../ref-config.md#firebird.driver.config.DriverConfig) and [`server_defaults`](../ref-config.md#firebird.driver.config.DriverConfig) configuration objects. A simple database connection is typically established with code such as this: @@ -110,13 +110,13 @@ con = connect('employee') ``` !!! info - `.connect()` for details. + [`connect()`](../ref-core.md#firebird.driver.core.connect) for details. ## Using create_database() This constructor returns connection to newly created database. It works in the same way -as `.connect()`, but utilizes additional database configuration options. +as [`connect()`](../ref-core.md#firebird.driver.core.connect), but utilizes additional database configuration options. It's possible to specify these options in code like this: @@ -188,7 +188,7 @@ con = create_database('mydb') ``` !!! info - `~firebird.driver.core.create_database()` for details. + [`create_database()`](../ref-core.md#firebird.driver.core.create_database) for details. ## Deleting databases @@ -201,7 +201,7 @@ it may even have dependent shadow databases. Although the database engine recognizes a `DROP DATABASE` SQL statement, support for that statement is limited to the `isql` command-line administration utility. However, the engine supports the deletion of databases via an API call, which `firebird-driver` exposes as -`~.Connection.drop_database` method in `.Connection` class. So, to drop a database +[`drop_database`](../ref-core.md#firebird.driver.core.Connection.drop_database) method in [`Connection`](../ref-core.md#firebird.driver.core.Connection) class. So, to drop a database you need to connect to it first. **Example:** @@ -218,26 +218,26 @@ con.drop_database() ``` !!! info - `.Connection.drop_database()` for details. + [`Connection.drop_database()`](../ref-core.md#firebird.driver.core.Connection.drop_database) for details. ## Connection object -`.Connection` object represents a direct link to database, and works as +[`Connection`](../ref-core.md#firebird.driver.core.Connection) object represents a direct link to database, and works as gateway for next operations with it: -* [Executing SQL Statements](executing-sql-statements.md#executing-sql-statements): methods `~.Connection.execute_immediate()` and `~.Connection.cursor()`. -* [Dropping database](databases.md#deleting-databases): method `~.Connection.drop_database()`. -* [Transanction management](transanction-management.md#transanction-management): methods `~.Connection.begin()`, `~.Connection.commit()`, - `~.Connection.rollback()`, `~.Connection.savepoint()`, `~.Connection.transaction_manager()`, - `~.Connection.is_active()`, and attributes `~.Connection.main_transaction`, - `~.Connection.query_transaction`, `~.Connection.transactions` and `~.Connection.default_tpb`. -* Work with [Database Events](database-events.md#database-events): method `~.Connection.event_collector`. -* [Getting information about connection](databases.md#getting-information-about-connection): methods `~.Connection.is_closed()` and - `~.Connection.ping()` and attributes `~.Connection.dsn`, `~.Connection.charset` - and `~.Connection.sql_dialect`. -* [Getting information about database](databases.md#getting-information-about-database): attribute `~.Connection.info`. -* [Closing the connection](databases.md#closing-the-connection): method `~.Connection.close()` +* [Executing SQL Statements](executing-sql-statements.md#executing-sql-statements): methods [`execute_immediate()`](../ref-core.md#firebird.driver.core.Connection.execute_immediate) and [`cursor()`](../ref-core.md#firebird.driver.core.Connection.cursor). +* [Dropping database](databases.md#deleting-databases): method [`drop_database()`](../ref-core.md#firebird.driver.core.Connection.drop_database). +* [Transactions](transactions.md#transactions): methods [`begin()`](../ref-core.md#firebird.driver.core.Connection.begin), [`commit()`](../ref-core.md#firebird.driver.core.Connection.commit), + [`rollback()`](../ref-core.md#firebird.driver.core.Connection.rollback), [`savepoint()`](../ref-core.md#firebird.driver.core.Connection.savepoint), [`transaction_manager()`](../ref-core.md#firebird.driver.core.Connection.transaction_manager), + [`is_active()`](../ref-core.md#firebird.driver.core.Connection.is_active), and attributes [`main_transaction`](../ref-core.md#firebird.driver.core.Connection.main_transaction), + [`query_transaction`](../ref-core.md#firebird.driver.core.Connection.query_transaction), [`transactions`](../ref-core.md#firebird.driver.core.Connection.transactions) and [`default_tpb`](../ref-core.md#firebird.driver.core.Connection). +* Work with [Database Events](database-events.md#database-events): method [`event_collector`](../ref-core.md#firebird.driver.core.Connection.event_collector). +* [Getting information about connection](databases.md#getting-information-about-connection): methods [`is_closed()`](../ref-core.md#firebird.driver.core.Connection.is_closed) and + [`ping()`](../ref-core.md#firebird.driver.core.Connection.ping) and attributes [`dsn`](../ref-core.md#firebird.driver.core.Connection.dsn), [`charset`](../ref-core.md#firebird.driver.core.Connection.charset) + and [`sql_dialect`](../ref-core.md#firebird.driver.core.Connection.sql_dialect). +* [Getting information about database](databases.md#getting-information-about-database): attribute [`info`](../ref-core.md#firebird.driver.core.Connection.info). +* [Closing the connection](databases.md#closing-the-connection): method [`close()`](../ref-core.md#firebird.driver.core.Connection.close) ## Closing the connection @@ -245,7 +245,7 @@ gateway for next operations with it: There are many local and server resources used by firebird-driver that must be properly managed, and disposed when they are no longer necessary. All objects that require proper finalization provide `close()` method that must be called when object is no longer needed. -The `.Connection` (and `.Server`) objects are the most important ones, as other most frequently +The [`Connection`](../ref-core.md#firebird.driver.core.Connection) (and [`Server`](../ref-core.md#firebird.driver.core.Server)) objects are the most important ones, as other most frequently used objects like cursors, prepared statements and transactions are typically associated with connections. @@ -269,10 +269,10 @@ with connect('employee') as con: !!! note - Objects that require proper finalization are: `.Connection`, `.TransactionManager` - and `.DistributedTransactionManager`, `.Statement`, `.BlobReader`, `.Cursor` and `.Server`. + Objects that require proper finalization are: [`Connection`](../ref-core.md#firebird.driver.core.Connection), [`TransactionManager`](../ref-core.md#firebird.driver.core.TransactionManager) + and [`DistributedTransactionManager`](../ref-core.md#firebird.driver.core.DistributedTransactionManager), [`Statement`](../ref-core.md#firebird.driver.core.Statement), [`BlobReader`](../ref-core.md#firebird.driver.core.BlobReader), [`Cursor`](../ref-core.md#firebird.driver.core.Cursor) and [`Server`](../ref-core.md#firebird.driver.core.Server). - Although only `.Connection` and `.Server` objects must be closed directly because + Although only [`Connection`](../ref-core.md#firebird.driver.core.Connection) and [`Server`](../ref-core.md#firebird.driver.core.Server) objects must be closed directly because all other objects are associated with them and thus closed when connection is closed, it's **recommended** to directly close any resource object obtained by your code when it's no longer needed (either directly by calling `close()` or using @@ -280,12 +280,12 @@ with connect('employee') as con: !!! important - All managed objects have `~object.__del__` method, which ensures that the object in + All managed objects have [`__del__`](https://docs.python.org/3/reference/datamodel.html#object.__del__) method, which ensures that the object in the active state is properly closed before it is destroyed by the Python memory manager. However, **the close operation may fail** as the state of your application could be arbitrary and the sequence in which objects are disposed by memory manager is not deterministic. - The `~object.__del__` methods should be thus considered as safe guard of last resort + The [`__del__`](https://docs.python.org/3/reference/datamodel.html#object.__del__) methods should be thus considered as safe guard of last resort that your code should not rely upon. To indicate that your code is not managing resources properly, the `ResourceWarning` is raises when active object is disposed by memory manager. @@ -297,27 +297,27 @@ with connect('employee') as con: delivery of resource warnings. !!! info - `.Connection.close()` for details. + [`Connection.close()`](../ref-core.md#firebird.driver.core.Connection.close) for details. ## Getting information about connection -Only (most useful) part of information associated with `.Connection` object is directly +Only (most useful) part of information associated with [`Connection`](../ref-core.md#firebird.driver.core.Connection) object is directly available: * It's possible to check whether Connection object is closed or not with - `~.Connection.is_closed()` method. + [`is_closed()`](../ref-core.md#firebird.driver.core.Connection.is_closed) method. * It's possible to check whether connection to the Firebird server is not broken with - `~.Connection.ping()` method. -* The DSN (fully qualified Firebird database connection string) is surfaced as `~.Connection.dsn` + [`ping()`](../ref-core.md#firebird.driver.core.Connection.ping) method. +* The DSN (fully qualified Firebird database connection string) is surfaced as [`dsn`](../ref-core.md#firebird.driver.core.Connection.dsn) read-only property. -* The character set used by Connection is surfaced as `~.Connection.charset` read-only property. -* The SQL dialect used by Connection is surfaced as `~.Connection.sql_dialect` read-only property. +* The character set used by Connection is surfaced as [`charset`](../ref-core.md#firebird.driver.core.Connection.charset) read-only property. +* The SQL dialect used by Connection is surfaced as [`sql_dialect`](../ref-core.md#firebird.driver.core.Connection.sql_dialect) read-only property. !!! tip Additional connection-specific information is currently held as `bytes` in protected - `Connection._dpb` attribute that could be processed using `~firebird.driver.core.DPB` object. + `Connection._dpb` attribute that could be processed using [`DPB`](../ref-core.md#firebird.driver.core.DPB) object. ## Getting information about database @@ -326,19 +326,19 @@ available: Because the scope and type of database information depends on the version of the Firebird server and database ODS, this information is made available through a separate class - `.DatabaseInfoProvider`. The `.Connection.info` property provides access to - instance of `.DatabaseInfoProvider` or it's **ancestor** class according to ODS of attached + [`DatabaseInfoProvider`](../ref-core.md#firebird.driver.core.DatabaseInfoProvider). The [`Connection.info`](../ref-core.md#firebird.driver.core.Connection.info) property provides access to + instance of [`DatabaseInfoProvider`](../ref-core.md#firebird.driver.core.DatabaseInfoProvider) or it's **ancestor** class according to ODS of attached database and Firebird version. Although you may query the information directly from server using -`~firebird.driver.core.DatabaseInfoProvider3.get_info()` method (that wraps the Firebird -`.iAttachment.getInfo()` API call), the `.DatabaseInfoProvider` object +[`get_info()`](../ref-core.md#firebird.driver.core.DatabaseInfoProvider3.get_info) method (that wraps the Firebird +[`iAttachment_v3.get_info()`](../ref-intf.md#firebird.driver.interfaces.iAttachment_v3.get_info) API call), the [`DatabaseInfoProvider`](../ref-core.md#firebird.driver.core.DatabaseInfoProvider) object provides more convenient methods and properties for obtaining specific information directly. !!! note - Some information provided by `.DatabaseInfoProvider` properties - (like `~.DatabaseInfoProvider3.cache_hit_ratio`) could not be obtained via + Some information provided by [`DatabaseInfoProvider`](../ref-core.md#firebird.driver.core.DatabaseInfoProvider) properties + (like [`cache_hit_ratio`](../ref-core.md#firebird.driver.core.DatabaseInfoProvider3.cache_hit_ratio)) could not be obtained via `get_info()` method. **Example:** @@ -415,7 +415,7 @@ ID for next transaction: 308 ``` !!! info - `.DatabaseInfoProvider` for details. + [`DatabaseInfoProvider`](../ref-core.md#firebird.driver.core.DatabaseInfoProvider) for details. #### Getting information about Firebird version @@ -426,18 +426,18 @@ was introduced to Firebird thanks to its InterBase legacy (Firebird 1.0 is a for 6.0), as applications designed to work with InterBase can often work with Firebird without problems (and vice versa). -`.DatabaseInfoProvider` provides these version strings as two properties: +[`DatabaseInfoProvider`](../ref-core.md#firebird.driver.core.DatabaseInfoProvider) provides these version strings as two properties: -* `~.DatabaseInfoProvider.server_version` - Legacy InterBase-friendly version string. -* `~.DatabaseInfoProvider.firebird_version` - Firebird’s own version string. +* [`server_version`](../ref-core.md#firebird.driver.core.DatabaseInfoProvider.server_version) - Legacy InterBase-friendly version string. +* [`firebird_version`](../ref-core.md#firebird.driver.core.DatabaseInfoProvider.firebird_version) - Firebird’s own version string. However, this version string contains more information than version number. For example for -Linux Firebird 4.0.0 it’s ‘LI-T4.0.0.1963 Firebird 4.0 Beta 2’. So `.DatabaseInfoProvider` +Linux Firebird 4.0.0 it’s ‘LI-T4.0.0.1963 Firebird 4.0 Beta 2’. So [`DatabaseInfoProvider`](../ref-core.md#firebird.driver.core.DatabaseInfoProvider) provides two more properties for your convenience: -* `~.DatabaseInfoProvider.version` - Only Firebird version number. It’s a string with +* [`version`](../ref-core.md#firebird.driver.core.DatabaseInfoProvider.version) - Only Firebird version number. It’s a string with format: major.minor.subrelease.build -* `~.DatabaseInfoProvider.engine_version` - Engine (major.minor) version as (float) number. +* [`engine_version`](../ref-core.md#firebird.driver.core.DatabaseInfoProvider.engine_version) - Engine (major.minor) version as (float) number. **Example:** @@ -469,7 +469,7 @@ Particular Firebird features may also depend on specific support in database present automatically when database is created by particular engine verison that needs them, but Firebird engine may work with databases created by older versions and thus with older structure, so it could be necessary to consult also On-Disk Structure (ODS for short) -version. `.DatabaseInfoProvider` provides this number as `~.DatabaseInfoProvider.ods` (float) +version. [`DatabaseInfoProvider`](../ref-core.md#firebird.driver.core.DatabaseInfoProvider) provides this number as [`ods`](../ref-core.md#firebird.driver.core.DatabaseInfoProvider.ods) (float) property. **Example:** diff --git a/docs/docs/usage-guide/driver-hooks.md b/docs/docs/usage-guide/driver-hooks.md index b434915..8529771 100644 --- a/docs/docs/usage-guide/driver-hooks.md +++ b/docs/docs/usage-guide/driver-hooks.md @@ -12,7 +12,7 @@ Driver hooks are divided into several types exposed as enums in `firebird.driver ## APIHook -`.APIHook.LOADED` - This hook is invoked once when instance of `.FirebirdAPI` is created. +[`APIHook.LOADED`](../ref-hooks.md#firebird.driver.hooks.APIHook) - This hook is invoked once when instance of [`FirebirdAPI`](../ref-fbapi.md#firebird.driver.fbapi.FirebirdAPI) is created. It could be used for additional initialization tasks that require Firebird API, or to manipulate the FirebirdAPI instance itself before its use. @@ -21,25 +21,25 @@ by hook is ignored. ## ConnectionHook -* `.ConnectionHook.ATTACH_REQUEST` +* [`ConnectionHook.ATTACH_REQUEST`](../ref-hooks.md#firebird.driver.hooks.ConnectionHook) - This hook is invoked after all parameters are preprocessed and before `.Connection` is created. + This hook is invoked after all parameters are preprocessed and before [`Connection`](../ref-core.md#firebird.driver.core.Connection) is created. Hook routine must have signature: `hook_func(dsn: str, dpb: bytes) -> Optional[Connection]` where `dpb` is Database Parameter Buffer that would be used to create the attachment to the - database defined by `dsn`. It may return `.Connection` (or subclass) instance or `None`. + database defined by `dsn`. It may return [`Connection`](../ref-core.md#firebird.driver.core.Connection) (or subclass) instance or `None`. First instance returned by any hook of this type will become the return value of caller function and other hooks of the same type are not invoked. -* `.ConnectionHook.ATTACHED` +* [`ConnectionHook.ATTACHED`](../ref-hooks.md#firebird.driver.hooks.ConnectionHook) - This hook is invoked just before `.Connection` (or subclass) instance is returned to the client + This hook is invoked just before [`Connection`](../ref-core.md#firebird.driver.core.Connection) (or subclass) instance is returned to the client application. Hook routine must have signature: `hook_func(con: Connection) -> None`. -* `.ConnectionHook.DETACH_REQUEST` +* [`ConnectionHook.DETACH_REQUEST`](../ref-hooks.md#firebird.driver.hooks.ConnectionHook) This hook is invoked before connection is closed. @@ -47,13 +47,13 @@ by hook is ignored. If any hook function returns True, connection is not closed. -* `.ConnectionHook.CLOSED` +* [`ConnectionHook.CLOSED`](../ref-hooks.md#firebird.driver.hooks.ConnectionHook) This hook is invoked after connection is closed. Hook routine must have signature: `hook_func(con: Connection) -> None`. -* `.ConnectionHook.DROPPED` +* [`ConnectionHook.DROPPED`](../ref-hooks.md#firebird.driver.hooks.ConnectionHook) This hook is invoked after database is dropped (and connection is closed). @@ -61,9 +61,9 @@ by hook is ignored. ## ServerHook -* `.ServerHook.ATTACHED` +* [`ServerHook.ATTACHED`](../ref-hooks.md#firebird.driver.hooks.ServerHook) - This hook is invoked before `.Server` instance is returned. + This hook is invoked before [`Server`](../ref-core.md#firebird.driver.core.Server) instance is returned. Hook routine must have signature: `hook_func(srv: Server) -> None`. diff --git a/docs/docs/usage-guide/driver-structure.md b/docs/docs/usage-guide/driver-structure.md index 3e17d65..48b2ea9 100644 --- a/docs/docs/usage-guide/driver-structure.md +++ b/docs/docs/usage-guide/driver-structure.md @@ -21,16 +21,16 @@ hooks, or to implement your own callback interfaces. be extended even in maintenance releases, the driver isolates volatile functionality into special class hierarchies. - For example information about database (provided via `~.iAttachment_v3.get_info()` API - call) is isolated into separate `.DatabaseInfoProvider` class hierarchy. - The `.Connection.info` attribute then provides access to instance of appropriate class - - `.DatabaseInfoProvider` or its ancestor - for connected database. - The `.DatabaseInfoProvider` class **always** provides functionality of most recent + For example information about database (provided via [`get_info()`](../ref-intf.md#firebird.driver.interfaces.iAttachment_v3.get_info) API + call) is isolated into separate [`DatabaseInfoProvider`](../ref-core.md#firebird.driver.core.DatabaseInfoProvider) class hierarchy. + The [`Connection.info`](../ref-core.md#firebird.driver.core.Connection.info) attribute then provides access to instance of appropriate class + - [`DatabaseInfoProvider`](../ref-core.md#firebird.driver.core.DatabaseInfoProvider) or its ancestor - for connected database. + The [`DatabaseInfoProvider`](../ref-core.md#firebird.driver.core.DatabaseInfoProvider) class **always** provides functionality of most recent Firebird version supported by driver. This layout has several important consequences: - 1. The `.DatabaseInfoProvider` class may change in major driver release if new Firebird + 1. The [`DatabaseInfoProvider`](../ref-core.md#firebird.driver.core.DatabaseInfoProvider) class may change in major driver release if new Firebird functionality is introduced. This normally represent no problems for client application as backward compatibility is guaranteed. 2. You should check the class hierarchy for "evolving" classes when you start using the @@ -43,11 +43,11 @@ hooks, or to implement your own callback interfaces. !!! note - The same apply for low-level API (`~firebird.driver.interfaces`) with difference + The same apply for low-level API ([`interfaces`](../ref-intf.md)) with difference that they may change in minor driver releases (because API could be extended in Firebird maintenance releases). !!! info - `.DatabaseInfoProvider`, `.TransactionInfoProvider`, `.ServerInfoProvider`, - `.ServerDbServices`, `.ServerUserServices` and `.ServerTraceServices`. + [`DatabaseInfoProvider`](../ref-core.md#firebird.driver.core.DatabaseInfoProvider), [`TransactionInfoProvider`](../ref-core.md#firebird.driver.core.TransactionInfoProvider), [`ServerInfoProvider`](../ref-core.md#firebird.driver.core.ServerInfoProvider), + [`ServerDbServices`](../ref-core.md#firebird.driver.core.ServerDbServices), [`ServerUserServices`](../ref-core.md#firebird.driver.core.ServerUserServices) and [`ServerTraceServices`](../ref-core.md#firebird.driver.core.ServerTraceServices). diff --git a/docs/docs/usage-guide/executing-sql-statements.md b/docs/docs/usage-guide/executing-sql-statements.md index a00f303..ebc9e90 100644 --- a/docs/docs/usage-guide/executing-sql-statements.md +++ b/docs/docs/usage-guide/executing-sql-statements.md @@ -2,39 +2,39 @@ Firebird-driver implements two ways for execution of SQL commands against connected database: -* `~.Connection.execute_immediate` - for execution of SQL commands that don't return any result. -* `.Cursor` objects that offer rich interface for execution of SQL commands and fetching their results. +* [`execute_immediate`](../ref-core.md#firebird.driver.core.Connection.execute_immediate) - for execution of SQL commands that don't return any result. +* [`Cursor`](../ref-core.md#firebird.driver.core.Cursor) objects that offer rich interface for execution of SQL commands and fetching their results. ## Cursor object -Because `.Cursor` objects always operate in context of single `.Connection` (and `.TransactionManager`), -`.Cursor` instances are not created directly, but by constructor method. Python DB API 2.0 assumes +Because [`Cursor`](../ref-core.md#firebird.driver.core.Cursor) objects always operate in context of single [`Connection`](../ref-core.md#firebird.driver.core.Connection) (and [`TransactionManager`](../ref-core.md#firebird.driver.core.TransactionManager)), +[`Cursor`](../ref-core.md#firebird.driver.core.Cursor) instances are not created directly, but by constructor method. Python DB API 2.0 assumes that if database engine supports transactions, it supports only one transaction per connection, -hence it defines constructor method `~.Connection.cursor` (and other transaction-related methods) -as part of `.Connection` interface. However, Firebird supports multiple independent transactions +hence it defines constructor method [`cursor`](../ref-core.md#firebird.driver.core.Connection.cursor) (and other transaction-related methods) +as part of [`Connection`](../ref-core.md#firebird.driver.core.Connection) interface. However, Firebird supports multiple independent transactions per connection. To conform to Python DB API, firebird-driver uses concept of internal -`~.Connection.main_transaction` and secondary `~.Connection.transactions`. Cursor constructor is -primarily defined by `.TransactionManager`, and Cursor constructor on `.Connection` is therefore +[`main_transaction`](../ref-core.md#firebird.driver.core.Connection.main_transaction) and secondary [`transactions`](../ref-core.md#firebird.driver.core.Connection.transactions). Cursor constructor is +primarily defined by [`TransactionManager`](../ref-core.md#firebird.driver.core.TransactionManager), and Cursor constructor on [`Connection`](../ref-core.md#firebird.driver.core.Connection) is therefore a shortcut for `main_transaction.cursor()`. -`.Cursor` objects are used for next operations: +[`Cursor`](../ref-core.md#firebird.driver.core.Cursor) objects are used for next operations: -* Execution of SQL Statemets: methods `~.Cursor.execute()`, `~.Cursor.executemany()`, `~.Cursor.open()` - and `~.Cursor.callproc()`. -* Creating `.Statement` objects for efficient repeated execution of SQL statements, and to obtain - additional information about SQL statements (like execution `~.Statement.plan`): method `~.Cursor.prepare()`. -* [Fetching results](executing-sql-statements.md#fetching-data-from-server): methods `~.Cursor.fetchone()`, `~.Cursor.fetchmany()`, - `~.Cursor.fetchall()`, `~.Cursor.fetch_next()`, `~.Cursor.fetch_prior()`, `~.Cursor.fetch_first()`, - `~.Cursor.fetch_last()`, `~.Cursor.fetch_absolute()` and `~.Cursor.fetch_relative()`. +* Execution of SQL Statemets: methods [`execute()`](../ref-core.md#firebird.driver.core.Cursor.execute), [`executemany()`](../ref-core.md#firebird.driver.core.Cursor.executemany), [`open()`](../ref-core.md#firebird.driver.core.Cursor.open) + and [`callproc()`](../ref-core.md#firebird.driver.core.Cursor.callproc). +* Creating [`Statement`](../ref-core.md#firebird.driver.core.Statement) objects for efficient repeated execution of SQL statements, and to obtain + additional information about SQL statements (like execution [`plan`](../ref-core.md#firebird.driver.core.Statement.plan)): method [`prepare()`](../ref-core.md#firebird.driver.core.Cursor.prepare). +* [Fetching results](executing-sql-statements.md#fetching-data-from-server): methods [`fetchone()`](../ref-core.md#firebird.driver.core.Cursor.fetchone), [`fetchmany()`](../ref-core.md#firebird.driver.core.Cursor.fetchmany), + [`fetchall()`](../ref-core.md#firebird.driver.core.Cursor.fetchall), [`fetch_next()`](../ref-core.md#firebird.driver.core.Cursor.fetch_next), [`fetch_prior()`](../ref-core.md#firebird.driver.core.Cursor.fetch_prior), [`fetch_first()`](../ref-core.md#firebird.driver.core.Cursor.fetch_first), + [`fetch_last()`](../ref-core.md#firebird.driver.core.Cursor.fetch_last), [`fetch_absolute()`](../ref-core.md#firebird.driver.core.Cursor.fetch_absolute) and [`fetch_relative()`](../ref-core.md#firebird.driver.core.Cursor.fetch_relative). ## SQL Execution Basics There are five methods how to execute SQL commands: -1. `.Connection.execute_immediate()` or `.TransactionManager.execute_immediate()` for SQL commands +1. [`Connection.execute_immediate()`](../ref-core.md#firebird.driver.core.Connection.execute_immediate) or [`TransactionManager.execute_immediate()`](../ref-core.md#firebird.driver.core.TransactionManager.execute_immediate) for SQL commands that don't return any result, and are not executed frequently. This method also **doesn't** support either [parameterized statements](executing-sql-statements.md#parameterized-statements) or [prepared statements](executing-sql-statements.md#prepared-statements). @@ -44,7 +44,7 @@ There are five methods how to execute SQL commands: This method is efficient for `administrative` and [DDL](http://en.wikipedia.org/wiki/Data_Definition_Language) SQL commands, like `DROP`, `CREATE` or `ALTER` commands, `SET STATISTICS` etc. -2. `.Cursor.execute()` for SQL commands that return result sets, i.e. sequence of `rows` of the same +2. [`Cursor.execute()`](../ref-core.md#firebird.driver.core.Cursor.execute) for SQL commands that return result sets, i.e. sequence of `rows` of the same structure, and sequence has unknown number of `rows` (including zero). Each row of the sequence can be read only once, and is returned in the order it is read from the server. @@ -53,7 +53,7 @@ There are five methods how to execute SQL commands: This method is preferred for all `SELECT` and other [DML](http://en.wikipedia.org/wiki/Data_Manipulation_Language) statements, or any statement that is executed frequently, either `as is` or in `parameterized` form. -3. `.Cursor.executemany()` for execution of single parameterized SQL command with various set +3. [`Cursor.executemany()`](../ref-core.md#firebird.driver.core.Cursor.executemany) for execution of single parameterized SQL command with various set of parameters. !!! important @@ -63,7 +63,7 @@ There are five methods how to execute SQL commands: it's possible to access the result set **only** from last executed command, so this method should not be used for SQL commands that return results. -4. `.Cursor.open()` for SQL command that return result sets, i.e. sequence of `rows` of the same +4. [`Cursor.open()`](../ref-core.md#firebird.driver.core.Cursor.open) for SQL command that return result sets, i.e. sequence of `rows` of the same structure, and sequence has unknown number of `rows` (including zero). Instead of just fetching rows sequentially in a forward direction like `execute()`, this method allows flexible navigation through an open cursor set both backwards and forwards. Rows next to, prior to and relative to @@ -72,7 +72,7 @@ There are five methods how to execute SQL commands: !!! info [Scrollable cursors](executing-sql-statements.md#scrollable-cursors) for details. -5. `.Cursor.callproc()` for execution of `Stored procedures` that always return exactly one set +5. [`Cursor.callproc()`](../ref-core.md#firebird.driver.core.Cursor.callproc) for execution of `Stored procedures` that always return exactly one set of values. !!! note @@ -83,41 +83,41 @@ There are five methods how to execute SQL commands: ## Fetching data from server Result of SQL statement execution consists from sequence of zero to unknown number of `rows`, -where each `row` is a set of exactly the same number of values. `.Cursor` object offer number +where each `row` is a set of exactly the same number of values. [`Cursor`](../ref-core.md#firebird.driver.core.Cursor) object offer number of different methods for fetching these `rows`, that should satisfy all your specific needs: -* `~.Cursor.fetchone()` - Returns the next row of a query result set, or `None` when no more data +* [`fetchone()`](../ref-core.md#firebird.driver.core.Cursor.fetchone) - Returns the next row of a query result set, or `None` when no more data is available. !!! tip Cursor supports the [iterator protocol](https://docs.python.org/3/library/stdtypes.html#iterator-types), yielding tuples of values - like `~.Cursor.fetchone()`. + like [`fetchone()`](../ref-core.md#firebird.driver.core.Cursor.fetchone). -* `~.Cursor.fetchmany()` - Returns the next set of rows of a query result, returning a sequence +* [`fetchmany()`](../ref-core.md#firebird.driver.core.Cursor.fetchmany) - Returns the next set of rows of a query result, returning a sequence of sequences (e.g. a list of tuples). An empty sequence is returned when no more rows are available. The number of rows to fetch per call is specified by the parameter. If it is not given, the - cursor’s `~.Cursor.arraysize` determines the number of rows to be fetched. The method does try + cursor’s [`arraysize`](../ref-core.md#firebird.driver.core.Cursor) determines the number of rows to be fetched. The method does try to fetch as many rows as indicated by the size parameter. If this is not possible due to the specified number of rows not being available, fewer rows may be returned. !!! note - The default value of `~.Cursor.arraysize` is `1`, so without paremeter it's equivalent to - `~.Cursor.fetchone()`, but returns list of `rows`, instead actual `row` directly. + The default value of [`arraysize`](../ref-core.md#firebird.driver.core.Cursor) is `1`, so without paremeter it's equivalent to + [`fetchone()`](../ref-core.md#firebird.driver.core.Cursor.fetchone), but returns list of `rows`, instead actual `row` directly. -* `~.Cursor.fetchall()` - Returns all (remaining) rows of a query result as list of tuples, +* [`fetchall()`](../ref-core.md#firebird.driver.core.Cursor.fetchall) - Returns all (remaining) rows of a query result as list of tuples, where each tuple is one row of returned values. !!! tip This method can potentially return huge amount of data, that may exhaust available memory. - If you need just `iteration` over potentially big result set, use loops with `~.Cursor.fetchone()` + If you need just `iteration` over potentially big result set, use loops with [`fetchone()`](../ref-core.md#firebird.driver.core.Cursor.fetchone) or Cursor's built-in support for [iterator protocol](https://docs.python.org/3/library/stdtypes.html#iterator-types) instead this method. -* Call to `~.Cursor.execute()` returns `self` (Cursor instance) that itself supports the - [iterator protocol](https://docs.python.org/3/library/stdtypes.html#iterator-types), yielding tuples of values like `~.Cursor.fetchone()`. +* Call to [`execute()`](../ref-core.md#firebird.driver.core.Cursor.execute) returns `self` (Cursor instance) that itself supports the + [iterator protocol](https://docs.python.org/3/library/stdtypes.html#iterator-types), yielding tuples of values like [`fetchone()`](../ref-core.md#firebird.driver.core.Cursor.fetchone). !!! important @@ -154,8 +154,8 @@ with connect('employee', user='SYSDBA', password='masterkey') as con: !!! important - Method `.Cursor.executemany()` is not intended for operations that return results, - so it does **NOT** returns `self` like `.Cursor.execute()`, and you can't use calls + Method [`Cursor.executemany()`](../ref-core.md#firebird.driver.core.Cursor.executemany) is not intended for operations that return results, + so it does **NOT** returns `self` like [`Cursor.execute()`](../ref-core.md#firebird.driver.core.Cursor.execute), and you can't use calls to this method as iterator. @@ -163,26 +163,26 @@ with connect('employee', user='SYSDBA', password='masterkey') as con: ## Scrollable cursors -SQL statements executed by `.Cursor.open()` have scrollable result set that could be +SQL statements executed by [`Cursor.open()`](../ref-core.md#firebird.driver.core.Cursor.open) have scrollable result set that could be navigated using next methods: -* `~.Cursor.fetch_next()` - Moves the cursor's current position to the next row and +* [`fetch_next()`](../ref-core.md#firebird.driver.core.Cursor.fetch_next) - Moves the cursor's current position to the next row and returns it. Returns `None` if the cursor is empty or already positioned at the last row. -* `~.Cursor.fetch_prior()` - Moves the cursor's current position to the prior row and +* [`fetch_prior()`](../ref-core.md#firebird.driver.core.Cursor.fetch_prior) - Moves the cursor's current position to the prior row and returns it. Returns `None` if the cursor is empty or already positioned at the first row. -* `~.Cursor.fetch_first()` - Moves the cursor's current position to the first row and +* [`fetch_first()`](../ref-core.md#firebird.driver.core.Cursor.fetch_first) - Moves the cursor's current position to the first row and returns it. Returns `None` if the cursor is empty. -* `~.Cursor.fetch_last()` - Moves the cursor's current position to the last row and +* [`fetch_last()`](../ref-core.md#firebird.driver.core.Cursor.fetch_last) - Moves the cursor's current position to the last row and returns it. Returns `None` if the cursor is empty. -* `~.Cursor.fetch_absolute()` - Moves the cursor's current position to the specified +* [`fetch_absolute()`](../ref-core.md#firebird.driver.core.Cursor.fetch_absolute) - Moves the cursor's current position to the specified and returns the located row. Returns `None` if is beyond the cursor's boundaries. -* `~.Cursor.fetch_relative()` - Moves the cursor's current position backward or forward +* [`fetch_relative()`](../ref-core.md#firebird.driver.core.Cursor.fetch_relative) - Moves the cursor's current position backward or forward by the specified and returns the located row. Returns `None` if the calculated position is beyond the cursor's boundaries. @@ -331,33 +331,33 @@ statement for repeated execution. This may save significant amount of server processing time, and result in better overall performance. Firebird-driver builds on this by encapsulating the Firebird SQL statement data -and related code into separate `.Statement` class, and implementing the `.Cursor` -class around it. The Cursor uses either an internally managed `.Statement` instance -to execute SQL commands provided as `string`, or uses `.Statement` instance +and related code into separate [`Statement`](../ref-core.md#firebird.driver.core.Statement) class, and implementing the [`Cursor`](../ref-core.md#firebird.driver.core.Cursor) +class around it. The Cursor uses either an internally managed [`Statement`](../ref-core.md#firebird.driver.core.Statement) instance +to execute SQL commands provided as `string`, or uses [`Statement`](../ref-core.md#firebird.driver.core.Statement) instance provided by your code as SQL command. -To get the (prepared) `.Statement` instance for later (repeated) execution, use -`~.Cursor.prepare()` method. You can then pass this instance to `~.Cursor.execute()`, -`~.Cursor.executemany()` or `~.Cursor.open()` instead `command string`. +To get the (prepared) [`Statement`](../ref-core.md#firebird.driver.core.Statement) instance for later (repeated) execution, use +[`prepare()`](../ref-core.md#firebird.driver.core.Cursor.prepare) method. You can then pass this instance to [`execute()`](../ref-core.md#firebird.driver.core.Cursor.execute), +[`executemany()`](../ref-core.md#firebird.driver.core.Cursor.executemany) or [`open()`](../ref-core.md#firebird.driver.core.Cursor.open) instead `command string`. -`.Statement` instances are bound to `.Connection` instance, and can't be used -with any other `.Connection`. Beside repeated execution they are also useful -to get information about statement (like its execution `~.Statement.plan` or -`~.Statement.type`) before its execution. +[`Statement`](../ref-core.md#firebird.driver.core.Statement) instances are bound to [`Connection`](../ref-core.md#firebird.driver.core.Connection) instance, and can't be used +with any other [`Connection`](../ref-core.md#firebird.driver.core.Connection). Beside repeated execution they are also useful +to get information about statement (like its execution [`plan`](../ref-core.md#firebird.driver.core.Statement.plan) or +[`type`](../ref-core.md#firebird.driver.core.Statement.type)) before its execution. !!! note - The internally managed `.Statement` instance is released when `.Cursor` is closed, + The internally managed [`Statement`](../ref-core.md#firebird.driver.core.Statement) instance is released when [`Cursor`](../ref-core.md#firebird.driver.core.Cursor) is closed, or before any new statement is executed. It means that if your code executes the same SQL command (passed as string) repeatedly without closing the cursor - between calls, the same `.Statement` instance is (re)used. + between calls, the same [`Statement`](../ref-core.md#firebird.driver.core.Statement) instance is (re)used. !!! important Implementation of Cursor in firebird-driver somewhat violates the Python DB API 2.0, - which requires that cursor will be unusable after call to `~.Cursor.close()`; and + which requires that cursor will be unusable after call to [`close()`](../ref-core.md#firebird.driver.core.Cursor.close); and an Error (or subclass) exception should be raised if any operation is attempted with - the cursor. In firebird-driver, the `.Cursor.close()` call only releases resources + the cursor. In firebird-driver, the [`Cursor.close()`](../ref-core.md#firebird.driver.core.Cursor.close) call only releases resources associated with executed statement like the result set, and you can't fetch data or query information about the SQL statement. However, you can use the cursor instance to execute new SQL commands. @@ -389,14 +389,14 @@ cur.executemany(insertStatement, inputRows) ``` !!! info - `.Statement` for details. + [`Statement`](../ref-core.md#firebird.driver.core.Statement) for details. ## Named Cursors To allow the Python programmer to perform scrolling **UPDATE** or **DELETE** via the **“SELECT ... FOR UPDATE”** syntax, the firebird-driver provides the read-only property -`.Cursor.name` and method `.Cursor.set_cursor_name()`. +[`Cursor.name`](../ref-core.md#firebird.driver.core.Cursor.name) and method [`Cursor.set_cursor_name()`](../ref-core.md#firebird.driver.core.Cursor.set_cursor_name). **Example Program:** @@ -453,11 +453,11 @@ con.commit() # If the procedure had any side effects, commit them. To **execute** a stored procedure and **access its output parameters**, you can choose from two options: -1. Method `.Cursor.callproc()` that **conforms to Python DB API 2.0**. This method - does not returns the output parameters directly, and you must call `.Cursor.fetchone()` +1. Method [`Cursor.callproc()`](../ref-core.md#firebird.driver.core.Cursor.callproc) that **conforms to Python DB API 2.0**. This method + does not returns the output parameters directly, and you must call [`Cursor.fetchone()`](../ref-core.md#firebird.driver.core.Cursor.fetchone) **exactly once** to retrieve them. -2. Method `.Cursor.call_procedure()` that returns output parameters directly +2. Method [`Cursor.call_procedure()`](../ref-core.md#firebird.driver.core.Cursor.call_procedure) that returns output parameters directly (or `None` if procedure does not have output parameters). **Examples:** diff --git a/docs/docs/usage-guide/logging-driver-activities.md b/docs/docs/usage-guide/logging-driver-activities.md index 142bcf4..9b1cdf0 100644 --- a/docs/docs/usage-guide/logging-driver-activities.md +++ b/docs/docs/usage-guide/logging-driver-activities.md @@ -1,27 +1,27 @@ # Logging driver activities -The firebird-driver supports [context-based logging system](https://firebird-base.readthedocs.io/en/latest/logging/) -provided by [firebird-base](https://firebird-base.rtfd.io) package through use of `~firebird.base.logging.LoggingIdMixin`. - -Classes that use `~firebird.base.logging.LoggingIdMixin`: - -* `.Connection` - Internally used objects have `_logging_id_` set to 'Transaction.Main', - 'Transaction.Query' and 'Cursor.internal'. The log context is not defined. -* `.TransactionManager` - The `_logging_id_` is set to 'Transaction'. The - `~.TransactionManager.log_context()` is the `.Connection`. -* `.DistributedTransactionManager` - The `_logging_id_` is set to 'DTransaction'. The - `~.DistributedTransactionManager.log_context()` is `~firebird.base.types.UNDEFINED`. -* `.Statement` - The `~.Statement.log_context()` is `.Connection`. -* `.BlobReader` - The `~.Statement.log_context()` is the owning object or `~firebird.base.types.UNDEFINED`. -* `.Cursor` - The `~.Cursor.log_context()` is `.Connection`. -* `.Server` - The log context is not defined. +The driver works with the [context-based logging system](https://firebird-base.readthedocs.io/en/latest/logging/) +provided by firebird-base. Pass a driver object to `firebird.base.logging.get_logger()` +to obtain a logger with an agent name and context. By default, the agent name is the +object's fully qualified class name. Set its `_agent_name_` attribute before obtaining +the logger to use a different name. + +The driver's `log_context` properties provide the context for these objects: + +* `TransactionManager`, `Statement`, and `Cursor`: their `Connection`. +* `DistributedTransactionManager`: `UNDEFINED` from `firebird.base.types`. +* `BlobReader`: its owner, or `UNDEFINED` when no owner is available. + +`Connection` and `Server` have no `log_context`, so their context is `None`. +The context field contains the context object itself; its displayed value depends +on that object's string representation, not its `_agent_name_`. **Example:** ```python import logging from firebird.base.logging import get_logger, LogLevel -from firebird.driver import connect, driver_config +from firebird.driver import Cursor, connect, driver_config # Helper function def execute(cur: Cursor, cmd: str) -> None: @@ -61,32 +61,32 @@ with connect('employee') as con: print("Custom logging ids") with connect('employee') as con: - con._logging_id_ = 'employee-1' + con._agent_name_ = 'employee-1' con_log = get_logger(con) con_log.info('Start') cur1 = con.cursor() - cur1._logging_id_ = 'cursor-1' + cur1._agent_name_ = 'cursor-1' cur2 = con.cursor() - cur2._logging_id_ = 'cursor-2' + cur2._agent_name_ = 'cursor-2' execute(cur1, 'select * from country') execute(cur2, 'select * from project') con_log.info('Stop') ``` -Output: +Representative output (`Connection[...]` contains a runtime handle): ```text Default logging ids -INFO : [Connection][UNDEFINED] Start -DEBUG : [Cursor][Connection] Execute [cmd='select * from country'] -DEBUG : [Cursor][Connection] Execute [cmd='select * from project'] -INFO : [Connection][UNDEFINED] Stop +INFO : [firebird.driver.core.Connection][None] Start +DEBUG : [firebird.driver.core.Cursor][Connection[...]] Execute [cmd='select * from country'] +DEBUG : [firebird.driver.core.Cursor][Connection[...]] Execute [cmd='select * from project'] +INFO : [firebird.driver.core.Connection][None] Stop Custom logging ids -INFO : [employee-1][UNDEFINED] Start -DEBUG : [cursor-1][employee-1] Execute [cmd='select * from country'] -DEBUG : [cursor-2][employee-1] Execute [cmd='select * from project'] -INFO : [employee-1][UNDEFINED] Stop +INFO : [employee-1][None] Start +DEBUG : [cursor-1][Connection[...]] Execute [cmd='select * from country'] +DEBUG : [cursor-2][Connection[...]] Execute [cmd='select * from project'] +INFO : [employee-1][None] Stop ``` You can also trace the driver activities using [trace/audit for class instances](https://firebird-base.readthedocs.io/en/latest/trace/) @@ -97,9 +97,8 @@ provided by [firebird-base](https://firebird-base.rtfd.io) package. ```python import logging from firebird.base.logging import get_logger, LogLevel -from firebird.base.trace import trace_manager, add_trace, trace_object, traced, TraceFlag -from firebird.driver import connect, driver_config -from firebird.driver.core import TransactionManager +from firebird.base.trace import trace_manager, add_trace, trace_object, TraceFlag +from firebird.driver import Connection, Cursor, TransactionManager, connect, driver_config # Helper function def execute(cur: Cursor, cmd: str) -> None: @@ -129,79 +128,36 @@ driver_config.register_database('employee', db_cfg) # Trace configuration # First: register classes and methods that could be traced trace_manager.register(Connection) -add_trace(Connection, 'close', traced) +add_trace(Connection, 'close') trace_manager.register(TransactionManager) -add_trace(TransactionManager, 'begin', traced) -add_trace(TransactionManager, 'commit', traced) -add_trace(TransactionManager, 'rollback', traced) +add_trace(TransactionManager, 'begin') +add_trace(TransactionManager, 'commit') +add_trace(TransactionManager, 'rollback') trace_manager.register(Cursor) -add_trace(Cursor, 'execute', traced) -add_trace(Cursor, 'close', traced) +add_trace(Cursor, 'execute') +add_trace(Cursor, 'close') # Activate trace/audit -trace_manager.trace |= (TraceFlag.ACTIVE | TraceFlag.BEFORE | TraceFlag.AFTER | TraceFlag.FAIL) +trace_manager.flags |= (TraceFlag.ACTIVE | TraceFlag.BEFORE | TraceFlag.AFTER | TraceFlag.FAIL) # Traced code with connect('employee') as con: trace_object(con) trace_object(con.main_transaction) - con._logging_id_ = 'employee-1' + con._agent_name_ = 'employee-1' cur1 = con.cursor() trace_object(cur1) - cur1._logging_id_ = 'cursor-1' + cur1._agent_name_ = 'cursor-1' cur2 = con.cursor() trace_object(cur2) - cur2._logging_id_ = 'cursor-2' + cur2._agent_name_ = 'cursor-2' execute(cur1, 'select * from country') execute(cur2, 'select * from project') con.commit() ``` -Sample output: - -```text -DEBUG : [cursor-1][employee-1] >>> execute(operation='select * from country', parameters=None) -DEBUG : [Transaction.Main][employee-1] >>> begin(tpb=None) -DEBUG : [Transaction.Main][employee-1] <<< begin[0.00672] -DEBUG : [cursor-1][employee-1] >>> close() -DEBUG : [cursor-1][employee-1] <<< close[0.00004] -DEBUG : [cursor-1][employee-1] <<< execute[0.01119] Result: cursor-1 -DEBUG : [cursor-2][employee-1] >>> execute(operation='select * from project', parameters=None) -DEBUG : [cursor-2][employee-1] >>> close() -DEBUG : [cursor-2][employee-1] <<< close[0.00002] -DEBUG : [cursor-2][employee-1] <<< execute[0.00352] Result: cursor-2 -DEBUG : [Transaction.Main][employee-1] >>> commit(retaining=False) -DEBUG : [cursor-1][employee-1] >>> close() -DEBUG : [cursor-1][employee-1] <<< close[0.00017] -DEBUG : [cursor-2][employee-1] >>> close() -DEBUG : [cursor-2][employee-1] <<< close[0.00012] -DEBUG : [Transaction.Main][employee-1] <<< commit[0.00225] -DEBUG : [employee-1][UNDEFINED] >>> close() -DEBUG : [employee-1][UNDEFINED] <<< close[0.00764] - - -``` -If you will remove the `con.commit()` from the example above, the output will change to: - -```text -DEBUG : [cursor-1][employee-1] >>> execute(operation='select * from country', parameters=None) -DEBUG : [Transaction.Main][employee-1] >>> begin(tpb=None) -DEBUG : [Transaction.Main][employee-1] <<< begin[0.00338] -DEBUG : [cursor-1][employee-1] >>> close() -DEBUG : [cursor-1][employee-1] <<< close[0.00003] -DEBUG : [cursor-1][employee-1] <<< execute[0.00730] Result: cursor-1 -DEBUG : [cursor-2][employee-1] >>> execute(operation='select * from project', parameters=None) -DEBUG : [cursor-2][employee-1] >>> close() -DEBUG : [cursor-2][employee-1] <<< close[0.00003] -DEBUG : [cursor-2][employee-1] <<< execute[0.00345] Result: cursor-2 -DEBUG : [employee-1][UNDEFINED] >>> close() -DEBUG : [Transaction.Main][employee-1] >>> rollback(retaining=False, savepoint=None) -DEBUG : [cursor-1][employee-1] >>> close() -DEBUG : [cursor-1][employee-1] <<< close[0.00016] -DEBUG : [cursor-2][employee-1] >>> close() -DEBUG : [cursor-2][employee-1] <<< close[0.00014] -DEBUG : [Transaction.Main][employee-1] <<< rollback[0.00171] -DEBUG : [employee-1][UNDEFINED] <<< close[0.01001] - - -``` +The trace records show calls before and after the traced methods. The `commit()` call +produces transaction commit records; without it, closing the connection rolls back +its active transaction. Agent names reflect `_agent_name_` when set, while the context +field for cursors and transaction managers displays their connection object. Exact +records, connection handles, and timings depend on the executed statements and server. diff --git a/docs/docs/usage-guide/transanction-management.md b/docs/docs/usage-guide/transactions.md similarity index 65% rename from docs/docs/usage-guide/transanction-management.md rename to docs/docs/usage-guide/transactions.md index 3cd953d..7408615 100644 --- a/docs/docs/usage-guide/transanction-management.md +++ b/docs/docs/usage-guide/transactions.md @@ -1,4 +1,4 @@ -# Transanction management +# Transactions For the sake of simplicity, firebird-driver lets the Python programmer ignore transaction management to the greatest extent allowed by the Python Database @@ -11,27 +11,28 @@ Remember that because of ACID, every data manipulation operation in the Firebird database engine takes place in the context of a transaction, including operations that are conceptually “read-only”, such as a typical SELECT. The client programmer of firebird-driver establishes a transaction implicitly by using any SQL execution -method, such as `.Connection.execute_immediate()`, `.Cursor.execute()`, or -`.Cursor.callproc()`. +method, such as [`Connection.execute_immediate()`](../ref-core.md#firebird.driver.core.Connection.execute_immediate), [`Cursor.execute()`](../ref-core.md#firebird.driver.core.Cursor.execute), or +[`Cursor.callproc()`](../ref-core.md#firebird.driver.core.Cursor.callproc). Although firebird-driver allows the programmer to pay little attention to transactions, it also exposes the full complement of the database engine’s advanced transaction -control features: [transaction parameters](transanction-management.md#transaction-parameters), [retaining transactions](transanction-management.md#retaining-transactions), [savepoints](transanction-management.md#savepoints), -and [distributed transactions](transanction-management.md#distributed-transactions). +control features: [transaction parameters](transactions.md#transaction-parameters), +[retaining transactions](transactions.md#retaining-transactions), [savepoints](transactions.md#savepoints), +and [distributed transactions](transactions.md#distributed-transactions). ## Basics -When it comes to transactions, Python Database API 2.0 specify that `.Connection` object +When it comes to transactions, Python Database API 2.0 specify that [`Connection`](../ref-core.md#firebird.driver.core.Connection) object has to respond to the following methods: -`.Connection.commit()` +[`Connection.commit()`](../ref-core.md#firebird.driver.core.Connection.commit) Commits any pending transaction to the database. Note that if the database supports an auto-commit feature, this must be initially off. An interface method may be provided to turn it back on. Database modules that do not support transactions should implement this method with void functionality. -`.Connection.rollback()` +[`Connection.rollback()`](../ref-core.md#firebird.driver.core.Connection.rollback) (optional) In case a database does provide transactions this method causes the the database to roll back to the start of any pending transaction. **Closing a connection @@ -39,7 +40,7 @@ has to respond to the following methods: In addition to the implicit transaction initiation required by Python Database API, firebird-driver allows the programmer to start transactions explicitly via the -`.Connection.begin()` method. Also `.Connection.savepoint()` method was added to provide +[`Connection.begin()`](../ref-core.md#firebird.driver.core.Connection.begin) method. Also [`Connection.savepoint()`](../ref-core.md#firebird.driver.core.Connection.savepoint) method was added to provide support for [Firebird SAVEPOINTs](http://www.firebirdsql.org/refdocs/langrefupd15-savepoint.html). But Python Database API 2.0 was created with assumption that connection can support only @@ -50,16 +51,16 @@ opened simultaneously to perform various tasks, which would require to open mult connections and thus consume more resources than necessary. Firebird-driver surfaces this Firebird feature by separating transaction management out -from `.Connection` into separate `.TransactionManager` objects. To comply with Python DB -API 2.0 requirements, `.Connection` object uses one `.TransactionManager` instance as -`main transaction`, and delegates `~.Connection.begin()`, -`~.Connection.savepoint()`, `~.Connection.commit()`, `~.Connection.rollback()` and -`~.Connection.execute_immediate()` calls to it. +from [`Connection`](../ref-core.md#firebird.driver.core.Connection) into separate [`TransactionManager`](../ref-core.md#firebird.driver.core.TransactionManager) objects. To comply with Python DB +API 2.0 requirements, [`Connection`](../ref-core.md#firebird.driver.core.Connection) object uses one [`TransactionManager`](../ref-core.md#firebird.driver.core.TransactionManager) instance as +`main transaction`, and delegates [`begin()`](../ref-core.md#firebird.driver.core.Connection.begin), +[`savepoint()`](../ref-core.md#firebird.driver.core.Connection.savepoint), [`commit()`](../ref-core.md#firebird.driver.core.Connection.commit), [`rollback()`](../ref-core.md#firebird.driver.core.Connection.rollback) and +[`execute_immediate()`](../ref-core.md#firebird.driver.core.Connection.execute_immediate) calls to it. !!! info More about using multiple transactions with the same connection in separate - [section](transanction-management.md#multiple_transactions). + [section](transactions.md#multiple_transactions). **Example:** @@ -73,12 +74,12 @@ with connect('employee', user='SYSDBA', password='masterkey') as con: # ======================================================================================== # # Transaction is started implicitly - cur.execute('insert into country values ('Oz','Crowns') + cur.execute('insert into country values (?,?)', ['Oz','Crowns']) con.commit() # commits active transaction # Again, transaction is started implicitly - cur.execute('insert into country values ('Barsoom','XXX') + cur.execute('insert into country values (?,?)', ['Barsoom','XXX']) con.rollback() # rolls back active transaction - cur.execute('insert into country values ('Pellucidar','Shells') + cur.execute('insert into country values (?,?)', ['Pellucidar','Shells']) # Commit was not performed before connection context was closed # This will roll back the transaction because Python DB API 2.0 @@ -88,14 +89,14 @@ with connect('employee', user='SYSDBA', password='masterkey') as con: ``` !!! info - `.TransactionManager` for details. + [`TransactionManager`](../ref-core.md#firebird.driver.core.TransactionManager) for details. ## Auto-commit Firebird-driver doesn't support `auto-commit` feature directly, but developers may achieve the similar result using `explicit` transaction start, taking advantage -of `.TransactionManager.default_action` and its default value (`~.DefaultAction.COMMIT`). +of [`TransactionManager.default_action`](../ref-core.md#firebird.driver.core.TransactionManager) and its default value ([`COMMIT`](../ref-types.md#firebird.driver.types.DefaultAction)). **Example:** @@ -106,11 +107,11 @@ with connect('employee', user='SYSDBA', password='masterkey') as con: cur = con.cursor() con.begin() - cur.execute('insert into country values ('Oz','Crowns') + cur.execute('insert into country values (?,?)', ['Oz','Crowns']) con.begin() # commits active transaction and starts new one - cur.execute('insert into country values ('Barsoom','XXX') + cur.execute('insert into country values (?,?)', ['Barsoom','XXX']) con.begin() # commits active transaction and starts new one - cur.execute('insert into country values ('Pellucidar','Shells') + cur.execute('insert into country values (?,?)', ['Pellucidar','Shells']) # However, commit is required before connection is closed, # because Python DB API 2.0 requires that closing connection @@ -129,23 +130,23 @@ the transaction has read and write access to tables, or read-only access, and whether or not other simultaneously active transactions can share table access with the transaction. -Transaction manager has `~.TransactionManager.default_tpb` attribute that can be +Transaction manager has [`default_tpb`](../ref-core.md#firebird.driver.core.TransactionManager) attribute that can be changed to set the default TPB to be used for all subsequent transactions started -by this manager. Also Connection have a `~.Connection.default_tpb` attribute, +by this manager. Also Connection have a [`default_tpb`](../ref-core.md#firebird.driver.core.Connection) attribute, but it's used to set the default TPB for all transactions managers subsequently -created for the connection (see `.Connection.transaction_manager()`). +created for the connection (see [`Connection.transaction_manager()`](../ref-core.md#firebird.driver.core.Connection.transaction_manager)). Alternatively, if the programmer only wants to set the TPB for a single transaction, -he can start a transaction explicitly via the `.Connection.begin()` or -`.TransactionManager.begin()` method and pass a TPB for that single transaction. +he can start a transaction explicitly via the [`Connection.begin()`](../ref-core.md#firebird.driver.core.Connection.begin) or +[`TransactionManager.begin()`](../ref-core.md#firebird.driver.core.TransactionManager.begin) method and pass a TPB for that single transaction. The TPB is a `bytes` value constructed from various tags and binary values, as defined by API. While you can construct the TPB manually, the firebird-driver provides several convenient ways for TPB construction: -1. The `.tpb()` function for simple TPBs. +1. The [`tpb()`](../ref-core.md#firebird.driver.core.tpb) function for simple TPBs. -2. The `~firebird.driver.core.TPB` class for complex TPBs (including table reservation etc.). +2. The [`TPB`](../ref-core.md#firebird.driver.core.TPB) class for complex TPBs (including table reservation etc.). **Examples:** @@ -174,13 +175,13 @@ complex_tpb = my_tpb.get_buffer() Because the scope and type of transaction information depends on the version of the Firebird server, this information is made available through a separate class - `.TransactionInfoProvider`. The `.TransactionManager.info` property provides access to - instance of `.TransactionInfoProvider` or it's **ancestor** class according to used + [`TransactionInfoProvider`](../ref-core.md#firebird.driver.core.TransactionInfoProvider). The [`TransactionManager.info`](../ref-core.md#firebird.driver.core.TransactionManager.info) property provides access to + instance of [`TransactionInfoProvider`](../ref-core.md#firebird.driver.core.TransactionInfoProvider) or it's **ancestor** class according to used Firebird version. Although you may query the information directly from server using -`~.TransactionInfoProvider3.get_info()` method (that wraps the Firebird `ITransaction.getInfo()` -API call), the `.TransactionInfoProvider` object provides more convenient methods and properties +[`get_info()`](../ref-core.md#firebird.driver.core.TransactionInfoProvider3.get_info) method (that wraps the Firebird `ITransaction.getInfo()` +API call), the [`TransactionInfoProvider`](../ref-core.md#firebird.driver.core.TransactionInfoProvider) object provides more convenient methods and properties for obtaining specific information directly. **Example:** @@ -219,7 +220,7 @@ ID of Oldest Snapshot Transaction: 352 ## Retaining transactions -The `~.TransactionManager.commit()` and `~.TransactionManager.rollback()` methods +The [`commit()`](../ref-core.md#firebird.driver.core.TransactionManager.commit) and [`rollback()`](../ref-core.md#firebird.driver.core.TransactionManager.rollback) methods accept an optional boolean keyword parameter `retaining` (**default False**) to indicate whether to recycle the transactional context of the transaction being resolved by the method call. @@ -253,10 +254,10 @@ Although Firebird savepoints are fully supported from SQL alone via the `SAVEPOI and `ROLLBACK TO ‘name’` statements, firebird-driver also exposes savepoints at the Python API level for the sake of convenience. -Call to method `.TransactionManager.savepoint()` establishes a savepoint with the specified -`name`. To roll back to a specific savepoint, call the `~.TransactionManager.rollback()` +Call to method [`TransactionManager.savepoint()`](../ref-core.md#firebird.driver.core.TransactionManager.savepoint) establishes a savepoint with the specified +`name`. To roll back to a specific savepoint, call the [`rollback()`](../ref-core.md#firebird.driver.core.TransactionManager.rollback) method and provide the name of the savepoint for the `savepoint` keyword parameter. If the -savepoint parameter of `~.TransactionManager.rollback()` is not specified, the active +savepoint parameter of [`rollback()`](../ref-core.md#firebird.driver.core.TransactionManager.rollback) is not specified, the active transaction is cancelled in its entirety, as required by the Python Database API Specification. The following program demonstrates savepoint manipulation via the firebird-driver API, @@ -328,17 +329,17 @@ After rolling back entirely, the contents of the table are: ## Using multiple transactions with the same connection To use additional transactions that could run simultaneously with -`main transaction` managed by `.Connection`, -create new `.TransactionManager` object calling `.Connection.transaction_manager()` +`main transaction` managed by [`Connection`](../ref-core.md#firebird.driver.core.Connection), +create new [`TransactionManager`](../ref-core.md#firebird.driver.core.TransactionManager) object calling [`Connection.transaction_manager()`](../ref-core.md#firebird.driver.core.Connection.transaction_manager) method. If you don't specify the optional `default_tpb` parameter, this new -`.TransactionManager` inherits the `~.Connection.default_tpb` from `.Connection`. -Physical transaction is not started when `.TransactionManager` instance is +[`TransactionManager`](../ref-core.md#firebird.driver.core.TransactionManager) inherits the [`default_tpb`](../ref-core.md#firebird.driver.core.Connection) from [`Connection`](../ref-core.md#firebird.driver.core.Connection). +Physical transaction is not started when [`TransactionManager`](../ref-core.md#firebird.driver.core.TransactionManager) instance is created, but implicitly when first SQL statement for cursor created from -this manager is executed, or explicitly via `.TransactionManager.begin()` call. +this manager is executed, or explicitly via [`TransactionManager.begin()`](../ref-core.md#firebird.driver.core.TransactionManager.begin) call. To execute statements in context of this additional transaction you have to -use `cursors` obtained directly from this `.TransactionManager` instance calling -its `~.TransactionManager.cursor()` method, or call `.TransactionManager.execute_immediate()` +use `cursors` obtained directly from this [`TransactionManager`](../ref-core.md#firebird.driver.core.TransactionManager) instance calling +its [`cursor()`](../ref-core.md#firebird.driver.core.TransactionManager.cursor) method, or call [`TransactionManager.execute_immediate()`](../ref-core.md#firebird.driver.core.TransactionManager.execute_immediate) method. **Example:** @@ -352,22 +353,22 @@ with connect('employee', user='SYSDBA', password='masterkey') as con: # Create new READ ONLY READ COMMITTED transaction ro_transaction = con.transaction_manager(tpb(Isolation.READ_COMMITTED_RECORD_VERSION, - access=TraAccessMode.READ)) + access_mode=TraAccessMode.READ)) # and cursor ro_cur = ro_transaction.cursor() - cur.execute('insert into country values ('Oz','Crowns') + cur.execute('insert into country values (?,?)', ['Oz','Crowns']) con.commit() # commits main transaction # Read data created by main transaction from second one - ro_cur.execute("select * from COUNTRY where COUNTRY = `Oz`") + ro_cur.execute("select * from COUNTRY where COUNTRY = 'Oz'") print(ro_cur.fetchall()) # Insert more data, but don't commit - cur.execute('insert into country values ('Barsoom','XXX') + cur.execute('insert into country values (?,?)', ['Barsoom','XXX']) # Read data created by main transaction from second one - ro_cur.execute("select * from COUNTRY where COUNTRY = `Barsoom`") + ro_cur.execute("select * from COUNTRY where COUNTRY = 'Barsoom'") print(ro_cur.fetchall()) ``` @@ -378,31 +379,31 @@ with connect('employee', user='SYSDBA', password='masterkey') as con: ## Distributed Transactions Distributed transactions are transactions that span multiple databases. -Firebird-driver provides this Firebird feature through `.DistributedTransactionManager` +Firebird-driver provides this Firebird feature through [`DistributedTransactionManager`](../ref-core.md#firebird.driver.core.DistributedTransactionManager) class. Instances of this class must be created manually, and managed transactions are fully independent from all other transactions, main or secondary, of member connections. -Similarly to `.TransactionManager`, distributed transactions are managed -through `~.DistributedTransactionManager.begin()`, -`~.DistributedTransactionManager.savepoint()`, `~.DistributedTransactionManager.commit()` -and `~.DistributedTransactionManager.rollback()` methods. -Additionally, `.DistributedTransactionManager` exposes method -`~.DistributedTransactionManager.prepare()` that explicitly initiates the +Similarly to [`TransactionManager`](../ref-core.md#firebird.driver.core.TransactionManager), distributed transactions are managed +through [`begin()`](../ref-core.md#firebird.driver.core.DistributedTransactionManager.begin), +[`savepoint()`](../ref-core.md#firebird.driver.core.DistributedTransactionManager.savepoint), [`commit()`](../ref-core.md#firebird.driver.core.DistributedTransactionManager.commit) +and [`rollback()`](../ref-core.md#firebird.driver.core.DistributedTransactionManager.rollback) methods. +Additionally, [`DistributedTransactionManager`](../ref-core.md#firebird.driver.core.DistributedTransactionManager) exposes method +[`prepare()`](../ref-core.md#firebird.driver.core.DistributedTransactionManager.prepare) that explicitly initiates the first phase of `Two-Phase Commit Protocol`. Transaction parameters are defined -similarly to `.TransactionManager` using `~.DistributedTransactionManager.default_tpb` -or as optional parameter to `~.DistributedTransactionManager.begin()` call. +similarly to [`TransactionManager`](../ref-core.md#firebird.driver.core.TransactionManager) using [`default_tpb`](../ref-core.md#firebird.driver.core.DistributedTransactionManager) +or as optional parameter to [`begin()`](../ref-core.md#firebird.driver.core.DistributedTransactionManager.begin) call. SQL statements that should belong to context of distributed transaction are -executed via `.Cursor` instances aquired through `.DistributedTransactionManager.cursor()` -method, or calling `.DistributedTransactionManager.execute_immediate()` method. +executed via [`Cursor`](../ref-core.md#firebird.driver.core.Cursor) instances aquired through [`DistributedTransactionManager.cursor()`](../ref-core.md#firebird.driver.core.DistributedTransactionManager.cursor) +method, or calling [`DistributedTransactionManager.execute_immediate()`](../ref-core.md#firebird.driver.core.DistributedTransactionManager.execute_immediate) method. !!! note - Because `.Cursor` instances can belong to only one `.Connection`, the - `~.DistributedTransactionManager.cursor()` method has mandatory parameter + Because [`Cursor`](../ref-core.md#firebird.driver.core.Cursor) instances can belong to only one [`Connection`](../ref-core.md#firebird.driver.core.Connection), the + [`cursor()`](../ref-core.md#firebird.driver.core.DistributedTransactionManager.cursor) method has mandatory parameter `connection`, to specify to which member connection cursor should belong. - The `~.DistributedTransactionManager.execute_immediate()` method operates + The [`execute_immediate()`](../ref-core.md#firebird.driver.core.DistributedTransactionManager.execute_immediate) method operates on **all** databases in *group*. **Example program:** @@ -536,10 +537,10 @@ db2: [(1, None), (2, None), (3, None)] ## Transaction Context Manager -Firebird-driver provides context manager `~firebird.driver.core.transaction` that allows automatic +Firebird-driver provides context manager [`transaction`](../ref-core.md#firebird.driver.core.transaction) that allows automatic transaction management using WITH statement. It can work with any object that supports `begin()`, `commit()` and `rollback()` methods, i.e. -`.Connection`, `.TransactionManager` or `.DistributedTransactionManager`. +[`Connection`](../ref-core.md#firebird.driver.core.Connection), [`TransactionManager`](../ref-core.md#firebird.driver.core.TransactionManager) or [`DistributedTransactionManager`](../ref-core.md#firebird.driver.core.DistributedTransactionManager). It starts transaction when WITH block is entered and commits it if no exception occurs within it, or calls `rollback()` otherwise. Exceptions raised in WITH @@ -563,11 +564,11 @@ with connect('employee', user='SYSDBA', password='masterkey') as con: cur.execute("insert into T (PK,C1) values (2,'AAA')") # Uses distributed transaction - with connect('employee2', user='SYSDBA', password='masterkey') as con2, - DistributedTransactionManager(con, con2) as dtm: + with (connect('employee2', user='SYSDBA', password='masterkey') as con2, + DistributedTransactionManager([con, con2]) as dtm): with transaction(dtm): - cur1 = cg.cursor(con) - cur2 = cg.cursor(con2) + cur1 = dtm.cursor(con) + cur2 = dtm.cursor(con2) cur1.execute("insert into T (PK,C1) values (3,'Local')") cur2.execute("insert into T (PK,C1) values (3,'Remote')") diff --git a/docs/docs/usage-guide/working-with-services.md b/docs/docs/usage-guide/working-with-services.md index ca757ae..69f8623 100644 --- a/docs/docs/usage-guide/working-with-services.md +++ b/docs/docs/usage-guide/working-with-services.md @@ -21,8 +21,8 @@ reason, the firebird-driver presents its own abstraction over the native API. ## Services API Connections All Services API operations are performed in the context of a `connection` to a specific -database server, represented by the `.Server` class. Similarly to database connections, -firebird-driver provides `.connect_server()` constructor function to create such connections. +database server, represented by the [`Server`](../ref-core.md#firebird.driver.core.Server) class. Similarly to database connections, +firebird-driver provides [`connect_server()`](../ref-core.md#firebird.driver.core.connect_server) constructor function to create such connections. This constructor has one positional and several keyword parameters. @@ -100,73 +100,73 @@ con = connect('main_server') !!! note - Like database connections, it's important to properly `~Server.close()` them + Like database connections, it's important to properly [`close()`](../ref-core.md#firebird.driver.core.Server.close) them when you don't need them anymore. -`.Server` object provides main infrastructure for communication with Firebird server services, +[`Server`](../ref-core.md#firebird.driver.core.Server) object provides main infrastructure for communication with Firebird server services, and manages number of objects that provide actual server services: -* The `.Server.info` property object provides [Server Configuration and State information](working-with-services.md#server-configuration-and-state-information). -* The `.Server.database` property object provides [Database options](working-with-services.md#database-options) and [Database maintenance](working-with-services.md#database-maintenance). -* The `.Server.user` property object provides [User maintenance](working-with-services.md#user-maintenance). -* The `.Server.trace` property object provides management of [Trace sessions](working-with-services.md#trace-sessions). +* The [`Server.info`](../ref-core.md#firebird.driver.core.Server.info) property object provides [Server Configuration and State information](working-with-services.md#server-configuration-and-state-information). +* The [`Server.database`](../ref-core.md#firebird.driver.core.Server.database) property object provides [Database options](working-with-services.md#database-options) and [Database maintenance](working-with-services.md#database-maintenance). +* The [`Server.user`](../ref-core.md#firebird.driver.core.Server.user) property object provides [User maintenance](working-with-services.md#user-maintenance). +* The [`Server.trace`](../ref-core.md#firebird.driver.core.Server.trace) property object provides management of [Trace sessions](working-with-services.md#trace-sessions). !!! info - `.connect_server()` and `.Server` for details. + [`connect_server()`](../ref-core.md#firebird.driver.core.connect_server) and [`Server`](../ref-core.md#firebird.driver.core.Server) for details. ## Text output from Services -Some services like `.ServerDbServices.backup()` may return significant amount of text. +Some services like [`ServerDbServices.backup()`](../ref-core.md#firebird.driver.core.ServerDbServices.backup) may return significant amount of text. Rather than return the whole text as single string value by methods that provide access to these services, firebird-driver isolated the transfer process to separate methods: -* `~.Server.readline()` - Similar to `file.readline`, returns next line of output from Service. -* `~.Server.readline_timed()` - Like `~.Server.readline()` but with timeout. -* `~.Server.readlines()` - Like `file.readlines`, returns list of output lines. -* Iteration over `.Server` object, because `.Server` has built-in support for [iterator protocol](https://docs.python.org/3/library/stdtypes.html#iterator-types). -* Using `callback` method provided by developer. Each `.Server` method that returns its result +* [`readline()`](../ref-core.md#firebird.driver.core.Server.readline) - Similar to `file.readline`, returns next line of output from Service. +* [`readline_timed()`](../ref-core.md#firebird.driver.core.Server.readline_timed) - Like [`readline()`](../ref-core.md#firebird.driver.core.Server.readline) but with timeout. +* [`readlines()`](../ref-core.md#firebird.driver.core.Server.readlines) - Like `file.readlines`, returns list of output lines. +* Iteration over [`Server`](../ref-core.md#firebird.driver.core.Server) object, because [`Server`](../ref-core.md#firebird.driver.core.Server) has built-in support for [iterator protocol](https://docs.python.org/3/library/stdtypes.html#iterator-types). +* Using `callback` method provided by developer. Each [`Server`](../ref-core.md#firebird.driver.core.Server) method that returns its result asynchronously accepts an optional parameter `callback`, which must be a function that accepts one string parameter. This method is then called with each output line coming from service. -* `~.Server.wait()` - Waits for Sevice to finish, ignoring rest of the output it may produce. +* [`wait()`](../ref-core.md#firebird.driver.core.Server.wait) - Waits for Sevice to finish, ignoring rest of the output it may produce. !!! important The Firebird server sends text output from services as packets, that could have two forms. - The method for packet construction used for text transfer is controlled by `.Server.mode` + The method for packet construction used for text transfer is controlled by [`Server.mode`](../ref-core.md#firebird.driver.core.Server) attribute with next possible values: - 1. `.SrvInfoCode.LINE` : A single line of text. - 2. `.SrvInfoCode.TO_EOF` : A block of text up to specified (buffer) size. + 1. [`SrvInfoCode.LINE`](../ref-types.md#firebird.driver.types.SrvInfoCode) : A single line of text. + 2. [`SrvInfoCode.TO_EOF`](../ref-types.md#firebird.driver.types.SrvInfoCode) : A block of text up to specified (buffer) size. Both methods have specific pros and cons: - 1. `~.SrvInfoCode.LINE` means more roundtrips and thus slower transfer of service output, + 1. [`LINE`](../ref-types.md#firebird.driver.types.SrvInfoCode) means more roundtrips and thus slower transfer of service output, but each line is sent to client immediately when it's available. - 2. `~.SrvInfoCode.TO_EOF` means fewer roundtrips so large output is transferred quickly, + 2. [`TO_EOF`](../ref-types.md#firebird.driver.types.SrvInfoCode) means fewer roundtrips so large output is transferred quickly, but service output is not sent until the transfer buffer is not full, or service stops. - **The default mode is** `~.SrvInfoCode.TO_EOF` **with 64K buffer.** + **The default mode is** [`TO_EOF`](../ref-types.md#firebird.driver.types.SrvInfoCode) **with 64K buffer.** !!! warning Until output is not fully fetched from service, any attempt to start another asynchronous service will fail with exception! This constraint is set by Firebird Service API. - You may check the status of asynchronous Services using `.Server.is_running()` method. + You may check the status of asynchronous Services using [`Server.is_running()`](../ref-core.md#firebird.driver.core.Server.is_running) method. - In cases when you're not interested in output produced by Service, call `~.Server.wait()` + In cases when you're not interested in output produced by Service, call [`wait()`](../ref-core.md#firebird.driver.core.Server.wait) to wait for service to complete. !!! important - Normally, requesting output with `~.Server.readline()` blocks until any output is - available from server. Bacuse this method is used by iteration over `.Server` and - `~.Server.readlines()` method, they will block as well. Most services produce output + Normally, requesting output with [`readline()`](../ref-core.md#firebird.driver.core.Server.readline) blocks until any output is + available from server. Bacuse this method is used by iteration over [`Server`](../ref-core.md#firebird.driver.core.Server) and + [`readlines()`](../ref-core.md#firebird.driver.core.Server.readlines) method, they will block as well. Most services produce output continuously and without (much) delay, so this is usually not a problem. However, some services (eg trace) can produce output at significantly slower intervals (if at all), which complicates the creation of responsive applications. In this case, it is necessary - to use the `~.Server.readline_timed()` method, which allows you to limit the waiting + to use the [`readline_timed()`](../ref-core.md#firebird.driver.core.Server.readline_timed) method, which allows you to limit the waiting time for the output. **Examples:** @@ -258,39 +258,39 @@ gbak:closing file, committing, and finishing. 74752 bytes written Because the scope and type of service information depends on the version of the Firebird server, this information is made available through a separate class - `.ServerInfoProvider`. The `.Server.info` property provides access to - instance of `.ServerInfoProvider` or it's **ancestor** class according to attached + [`ServerInfoProvider`](../ref-core.md#firebird.driver.core.ServerInfoProvider). The [`Server.info`](../ref-core.md#firebird.driver.core.Server.info) property provides access to + instance of [`ServerInfoProvider`](../ref-core.md#firebird.driver.core.ServerInfoProvider) or it's **ancestor** class according to attached Firebird server version. -`.ServerInfoProvider` methods and properties: +[`ServerInfoProvider`](../ref-core.md#firebird.driver.core.ServerInfoProvider) methods and properties: -* `~.ServerInfoProvider.get_log()` - Request the contents of the server’s log file (`firebird.log`). +* [`get_log()`](../ref-core.md#firebird.driver.core.ServerInfoProvider.get_log) - Request the contents of the server’s log file (`firebird.log`). This method is so-called `Async service` that only initiates log transfer. Actual log content could be read by one from many methods for [text output from Services](working-with-services.md#text-output-from-services) that - `.Server` provides . + [`Server`](../ref-core.md#firebird.driver.core.Server) provides . -* `~.ServerInfoProvider.version` - Returns Firebird server version as SEMVER string. +* [`version`](../ref-core.md#firebird.driver.core.ServerInfoProvider.version) - Returns Firebird server version as SEMVER string. -* `~.ServerInfoProvider.engine_version` - Firebird server version as . float value. +* [`engine_version`](../ref-core.md#firebird.driver.core.ServerInfoProvider.engine_version) - Firebird server version as . float value. -* `~.ServerInfoProvider.manager_version` - Firebird service manager version. +* [`manager_version`](../ref-core.md#firebird.driver.core.ServerInfoProvider.manager_version) - Firebird service manager version. -* `~.ServerInfoProvider.architecture` - Firebird server implementation description. +* [`architecture`](../ref-core.md#firebird.driver.core.ServerInfoProvider.architecture) - Firebird server implementation description. -* `~.ServerInfoProvider.home_directory` - Firebird server home directory. +* [`home_directory`](../ref-core.md#firebird.driver.core.ServerInfoProvider.home_directory) - Firebird server home directory. -* `~.ServerInfoProvider.security_database` - Security database. +* [`security_database`](../ref-core.md#firebird.driver.core.ServerInfoProvider.security_database) - Security database. -* `~.ServerInfoProvider.lock_directory` - Directory with lock file(s). +* [`lock_directory`](../ref-core.md#firebird.driver.core.ServerInfoProvider.lock_directory) - Directory with lock file(s). -* `~.ServerInfoProvider.message_directory` - Directory with message file(s). +* [`message_directory`](../ref-core.md#firebird.driver.core.ServerInfoProvider.message_directory) - Directory with message file(s). -* `~.ServerInfoProvider.capabilities` - Firebird server capabilities (as `.ServerCapability` flags). +* [`capabilities`](../ref-core.md#firebird.driver.core.ServerInfoProvider.capabilities) - Firebird server capabilities (as [`ServerCapability`](../ref-types.md#firebird.driver.types.ServerCapability) flags). -* `~.ServerInfoProvider.connection_count` - Current number of database attachments. +* [`connection_count`](../ref-core.md#firebird.driver.core.ServerInfoProvider.connection_count) - Current number of database attachments. -* `~.ServerInfoProvider.attached_databases` - List of attached databases. +* [`attached_databases`](../ref-core.md#firebird.driver.core.ServerInfoProvider.attached_databases) - List of attached databases. **Example:** @@ -343,10 +343,10 @@ srv.info.attached_databases=['/opt/firebird/examples/empbuild/employee.fdb'] ## Database options -Database options could be set using `.ServerDbServices` instance accessible via -`.Server.database` property. +Database options could be set using [`ServerDbServices`](../ref-core.md#firebird.driver.core.ServerDbServices) instance accessible via +[`Server.database`](../ref-core.md#firebird.driver.core.Server.database) property. -* `~.ServerDbServices.set_default_cache_size()` - Sets individual page cache size for database. +* [`set_default_cache_size()`](../ref-core.md#firebird.driver.core.ServerDbServices.set_default_cache_size) - Sets individual page cache size for database. ```python >>> from firebird.driver import connect_server @@ -355,7 +355,7 @@ Database options could be set using `.ServerDbServices` instance accessible via ``` -* `~.ServerDbServices.set_sweep_interval()` - Sets database sweep interval. +* [`set_sweep_interval()`](../ref-core.md#firebird.driver.core.ServerDbServices.set_sweep_interval) - Sets database sweep interval. ```python >>> from firebird.driver import connect_server @@ -364,7 +364,7 @@ Database options could be set using `.ServerDbServices` instance accessible via ``` -* `~.ServerDbServices.set_space_reservation()` - Sets space reservation option for database. +* [`set_space_reservation()`](../ref-core.md#firebird.driver.core.ServerDbServices.set_space_reservation) - Sets space reservation option for database. ```python >>> from firebird.driver import connect_server, DbSpaceReservation @@ -373,7 +373,7 @@ Database options could be set using `.ServerDbServices` instance accessible via ``` -* `~.ServerDbServices.set_write_mode()` - Sets database write mode (SYNC/ASYNC). +* [`set_write_mode()`](../ref-core.md#firebird.driver.core.ServerDbServices.set_write_mode) - Sets database write mode (SYNC/ASYNC). ```python >>> from firebird.driver import connect_server, DbWriteMode @@ -382,7 +382,7 @@ Database options could be set using `.ServerDbServices` instance accessible via ``` -* `~.ServerDbServices.set_access_mode()` - Sets database access mode (R/W or R/O). +* [`set_access_mode()`](../ref-core.md#firebird.driver.core.ServerDbServices.set_access_mode) - Sets database access mode (R/W or R/O). ```python >>> from firebird.driver import connect_server, DbAccessMode @@ -391,7 +391,7 @@ Database options could be set using `.ServerDbServices` instance accessible via ``` -* `~.ServerDbServices.set_sql_dialect()` - Sets database SQL dialect. +* [`set_sql_dialect()`](../ref-core.md#firebird.driver.core.ServerDbServices.set_sql_dialect) - Sets database SQL dialect. !!! warning @@ -406,7 +406,7 @@ Database options could be set using `.ServerDbServices` instance accessible via ``` -* `~.ServerDbServices.no_linger()` - Sets one-off override for database linger. +* [`no_linger()`](../ref-core.md#firebird.driver.core.ServerDbServices.no_linger) - Sets one-off override for database linger. ```python >>> from firebird.driver import connect_server @@ -421,16 +421,16 @@ Database options could be set using `.ServerDbServices` instance accessible via !!! important Because available database-related actions depends on the version of the Firebird - server, they are made available through a separate class `.ServerDbServices`. - The `.Server.database` property provides access to instance of `.ServerDbServices` or + server, they are made available through a separate class [`ServerDbServices`](../ref-core.md#firebird.driver.core.ServerDbServices). + The [`Server.database`](../ref-core.md#firebird.driver.core.Server.database) property provides access to instance of [`ServerDbServices`](../ref-core.md#firebird.driver.core.ServerDbServices) or it's **ancestor** class according to attached Firebird server version. -* `~.ServerDbServices3.get_statistics()` - Returns database statistics produced by gstat +* [`get_statistics()`](../ref-core.md#firebird.driver.core.ServerDbServices3.get_statistics) - Returns database statistics produced by gstat utility. This method is so-called `Async service` that only initiates report processing. Actual report content could be read by one from many methods for [text output from Services](working-with-services.md#text-output-from-services) that - `.Server` provides . + [`Server`](../ref-core.md#firebird.driver.core.Server) provides . ```python from firebird.driver import connect_server, SrvStatFlag @@ -442,11 +442,11 @@ Database options could be set using `.ServerDbServices` instance accessible via ``` -* `~.ServerDbServices3.backup()` - Performs logical (GBAK) database backup. +* [`backup()`](../ref-core.md#firebird.driver.core.ServerDbServices3.backup) - Performs logical (GBAK) database backup. This method is so-called `Async service` that only initiates the backup process. Output from gbak could be read by one from many methods for [text output from Services](working-with-services.md#text-output-from-services) that - `.Server` provides . + [`Server`](../ref-core.md#firebird.driver.core.Server) provides . ```python from firebird.driver import connect_server, SrvBackupFlag @@ -459,7 +459,7 @@ Database options could be set using `.ServerDbServices` instance accessible via ``` -* `~.ServerDbServices3.local_backup()` - Performs logical (GBAK) database backup into local byte +* [`local_backup()`](../ref-core.md#firebird.driver.core.ServerDbServices3.local_backup) - Performs logical (GBAK) database backup into local byte stream. ```python @@ -472,11 +472,11 @@ Database options could be set using `.ServerDbServices` instance accessible via ``` -* `~.ServerDbServices3.restore()` - Performs database restore from logical (GBAK) backup. +* [`restore()`](../ref-core.md#firebird.driver.core.ServerDbServices3.restore) - Performs database restore from logical (GBAK) backup. This method is so-called `Async service` that only initiates the restore process. Output from gbak could be read by one from many methods for [text output from Services](working-with-services.md#text-output-from-services) that - `.Server` provides . + [`Server`](../ref-core.md#firebird.driver.core.Server) provides . ```python from firebird.driver import connect_server, SrvRestoreFlag @@ -489,7 +489,7 @@ Database options could be set using `.ServerDbServices` instance accessible via ``` -* `~.ServerDbServices3.local_restore()` - Performs database restore from logical (GBAK) backup +* [`local_restore()`](../ref-core.md#firebird.driver.core.ServerDbServices3.local_restore) - Performs database restore from logical (GBAK) backup stored in local byte stream. ```python @@ -502,7 +502,7 @@ Database options could be set using `.ServerDbServices` instance accessible via ``` -* `~.ServerDbServices3.nbackup()` - Performs physical (NBACKUP) database backup. +* [`nbackup()`](../ref-core.md#firebird.driver.core.ServerDbServices3.nbackup) - Performs physical (NBACKUP) database backup. ```python from firebird.driver import connect_server @@ -511,7 +511,7 @@ Database options could be set using `.ServerDbServices` instance accessible via ``` -* `~.ServerDbServices3.nrestore()` - Performs restore from physical (NBACKUP) database +* [`nrestore()`](../ref-core.md#firebird.driver.core.ServerDbServices3.nrestore) - Performs restore from physical (NBACKUP) database backup. ```python @@ -522,7 +522,7 @@ Database options could be set using `.ServerDbServices` instance accessible via ``` -* `~.ServerDbServices3.shutdown()` - Database shutdown. +* [`shutdown()`](../ref-core.md#firebird.driver.core.ServerDbServices3.shutdown) - Database shutdown. ```python from firebird.driver import connect_server, ShutdownMode, ShutdownMethod @@ -532,7 +532,7 @@ Database options could be set using `.ServerDbServices` instance accessible via ``` -* `~.ServerDbServices3.bring_online()` - Bring previously shut down database back online. +* [`bring_online()`](../ref-core.md#firebird.driver.core.ServerDbServices3.bring_online) - Bring previously shut down database back online. ```python from firebird.driver import connect_server, OnlineMode @@ -541,7 +541,7 @@ Database options could be set using `.ServerDbServices` instance accessible via ``` -* `~.ServerDbServices3.sweep()` - Performs database sweep operation. +* [`sweep()`](../ref-core.md#firebird.driver.core.ServerDbServices3.sweep) - Performs database sweep operation. ```python from firebird.driver import connect_server @@ -550,11 +550,11 @@ Database options could be set using `.ServerDbServices` instance accessible via ``` -* `~.ServerDbServices3.validate()` - Performs database validation. +* [`validate()`](../ref-core.md#firebird.driver.core.ServerDbServices3.validate) - Performs database validation. This method is so-called `Async service` that only initiates the validation process. Output from validation could be read by one from many methods for [text output from Services](working-with-services.md#text-output-from-services) that - `.Server` provides . + [`Server`](../ref-core.md#firebird.driver.core.Server) provides . ```python from firebird.driver import connect_server @@ -564,7 +564,7 @@ Database options could be set using `.ServerDbServices` instance accessible via ``` -* `~.ServerDbServices3.repair()` - Performs database repair operation. +* [`repair()`](../ref-core.md#firebird.driver.core.ServerDbServices3.repair) - Performs database repair operation. ```python from firebird.driver import connect_server, SrvRepairFlag @@ -574,15 +574,15 @@ Database options could be set using `.ServerDbServices` instance accessible via ``` -* `~.ServerDbServices3.get_limbo_transaction_ids()` - Returns list of transactions in limbo. +* [`get_limbo_transaction_ids()`](../ref-core.md#firebird.driver.core.ServerDbServices3.get_limbo_transaction_ids) - Returns list of transactions in limbo. -* `~.ServerDbServices3.commit_limbo_transaction()` - Resolves limbo transaction with commit. +* [`commit_limbo_transaction()`](../ref-core.md#firebird.driver.core.ServerDbServices3.commit_limbo_transaction) - Resolves limbo transaction with commit. -* `~.ServerDbServices3.rollback_limbo_transaction()` - Resolves limbo transaction with rollback. +* [`rollback_limbo_transaction()`](../ref-core.md#firebird.driver.core.ServerDbServices3.rollback_limbo_transaction) - Resolves limbo transaction with rollback. -* `~.ServerDbServices.nfix_database` - Fixup database after filesystem copy. +* [`nfix_database`](../ref-core.md#firebird.driver.core.ServerDbServices.nfix_database) - Fixup database after filesystem copy. -* `~.ServerDbServices.set_replica_mode` - Manage replica database. +* [`set_replica_mode`](../ref-core.md#firebird.driver.core.ServerDbServices.set_replica_mode) - Manage replica database. ## User maintenance @@ -591,8 +591,8 @@ Database options could be set using `.ServerDbServices` instance accessible via Because user maintenance functionality may depend on the version of the Firebird server, this functionality is made available through a separate class - `.ServerUserServices`. The `.Server.user` property provides access to - instance of `.ServerUserServices` or it's **ancestor** class according to attached + [`ServerUserServices`](../ref-core.md#firebird.driver.core.ServerUserServices). The [`Server.user`](../ref-core.md#firebird.driver.core.Server.user) property provides access to + instance of [`ServerUserServices`](../ref-core.md#firebird.driver.core.ServerUserServices) or it's **ancestor** class according to attached Firebird server version. !!! tip @@ -603,17 +603,17 @@ Database options could be set using `.ServerDbServices` instance accessible via The SQL set of DDL commands for managing user accounts has been further enhanced in Firebird 3, thus improving the DDL capabilities in a way that exceeds capabilities of user management services. -* `~.ServerUserServices.get_all()` - Returns information about all users. +* [`get_all()`](../ref-core.md#firebird.driver.core.ServerUserServices.get_all) - Returns information about all users. -* `~.ServerUserServices.get()` - Returns information about specified users. +* [`get()`](../ref-core.md#firebird.driver.core.ServerUserServices.get) - Returns information about specified users. -* `~.ServerUserServices.add()` - Add new user. +* [`add()`](../ref-core.md#firebird.driver.core.ServerUserServices.add) - Add new user. -* `~.ServerUserServices.update()` - Update user information. +* [`update()`](../ref-core.md#firebird.driver.core.ServerUserServices.update) - Update user information. -* `~.ServerUserServices.delete()` - Delete user. +* [`delete()`](../ref-core.md#firebird.driver.core.ServerUserServices.delete) - Delete user. -* `~.ServerUserServices.exists()` - Returns True if user exists. +* [`exists()`](../ref-core.md#firebird.driver.core.ServerUserServices.exists) - Returns True if user exists. ## Trace sessions @@ -621,15 +621,15 @@ Database options could be set using `.ServerDbServices` instance accessible via !!! important Because trace functionality may depend on the version of the Firebird server, this - functionality is made available through a separate class `.ServerTraceServices`. - The `.Server.trace` property provides access to instance of `.ServerTraceServices` or + functionality is made available through a separate class [`ServerTraceServices`](../ref-core.md#firebird.driver.core.ServerTraceServices). + The [`Server.trace`](../ref-core.md#firebird.driver.core.Server.trace) property provides access to instance of [`ServerTraceServices`](../ref-core.md#firebird.driver.core.ServerTraceServices) or its **ancestor** class according to attached Firebird server version. -* `.ServerTraceServices.start()` - Start new trace session. Requires trace `configuration` and returns `Session ID`. +* [`ServerTraceServices.start()`](../ref-core.md#firebird.driver.core.ServerTraceServices.start) - Start new trace session. Requires trace `configuration` and returns `Session ID`. This method is so-called `Async service` that only starts the trace session. Output from trace session could be read by one from many methods for [text output from Services](working-with-services.md#text-output-from-services) - that `.Server` provides . + that [`Server`](../ref-core.md#firebird.driver.core.Server) provides . ```python from firebird.driver import connect_server @@ -659,10 +659,10 @@ Database options could be set using `.ServerDbServices` instance accessible via ``` -* `.ServerTraceServices.stop()` - Stop trace session. +* [`ServerTraceServices.stop()`](../ref-core.md#firebird.driver.core.ServerTraceServices.stop) - Stop trace session. -* `.ServerTraceServices.suspend()` - Suspend trace session. +* [`ServerTraceServices.suspend()`](../ref-core.md#firebird.driver.core.ServerTraceServices.suspend) - Suspend trace session. -* `.ServerTraceServices.resume()` - Resume trace session. +* [`ServerTraceServices.resume()`](../ref-core.md#firebird.driver.core.ServerTraceServices.resume) - Resume trace session. -* `.ServerTraceServices.sessions` - Dictionary with active trace sessions. The key is session ID, value is `.TraceSession` instance. +* [`ServerTraceServices.sessions`](../ref-core.md#firebird.driver.core.ServerTraceServices.sessions) - Dictionary with active trace sessions. The key is session ID, value is [`TraceSession`](../ref-types.md#firebird.driver.types.TraceSession) instance. diff --git a/docs/zensical.toml b/docs/zensical.toml index 36254e6..cdee3f7 100644 --- a/docs/zensical.toml +++ b/docs/zensical.toml @@ -12,7 +12,7 @@ nav = [ { "Databases" = "usage-guide/databases.md" }, { "Executing SQL Statements" = "usage-guide/executing-sql-statements.md" }, { "Data handling and conversions" = "usage-guide/data-handling-and-conversions.md" }, - { "Transanction management" = "usage-guide/transanction-management.md" }, + { "Transactions" = "usage-guide/transactions.md" }, { "Database Events" = "usage-guide/database-events.md" }, { "Working with Services" = "usage-guide/working-with-services.md" }, { "Logging driver activities" = "usage-guide/logging-driver-activities.md" }, From 578783c0359be6017f249ede7a170b4da4d860af Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Thu, 8 Oct 2026 21:28:18 +0200 Subject: [PATCH 17/48] Add llms.txt to documentation --- docs/zensical.toml | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/docs/zensical.toml b/docs/zensical.toml index cdee3f7..49ac896 100644 --- a/docs/zensical.toml +++ b/docs/zensical.toml @@ -54,3 +54,30 @@ docstring_style = "google" inherited_members = true show_root_heading = true show_source = true + +[project.plugins.llmstxt] +enabled = true +sections = { +"Usage Guide" = [ + "usage-guide/driver-structure.md" , + "usage-guide/configuration.md", + "usage-guide/databases.md", + "usage-guide/executing-sql-statements.md", + "usage-guide/data-handling-and-conversions.md", + "usage-guide/transactions.md", + "usage-guide/database-events.md", + "usage-guide/working-with-services.md", + "usage-guide/logging-driver-activities.md", + "usage-guide/driver-hooks.md", + ], + "Python DB API compliance" = ["python-db-api-compliance.md",], + "Reference" = [ + "ref-main.md", + "ref-types.md", + "ref-config.md", + "ref-core.md", + "ref-hooks.md", + "ref-intf.md", + "ref-fbapi.md", + ], +} From 35420eb32744ccdacdb955c1f69b42af22e3aade Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Thu, 8 Oct 2026 21:35:29 +0200 Subject: [PATCH 18/48] Adjustment --- docs/zensical.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/zensical.toml b/docs/zensical.toml index 49ac896..6ab57e9 100644 --- a/docs/zensical.toml +++ b/docs/zensical.toml @@ -57,6 +57,7 @@ show_source = true [project.plugins.llmstxt] enabled = true +markdown_description = "For driver version 2.0.3" sections = { "Usage Guide" = [ "usage-guide/driver-structure.md" , From 6f7f2ac22950097c145e839d98714ae824cf7db7 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Thu, 8 Oct 2026 22:01:54 +0200 Subject: [PATCH 19/48] Add AI skill --- README.md | 36 +++++++++++++ skills/firebird-driver-python/SKILL.md | 37 +++++++++++++ .../references/connections-resources.md | 52 +++++++++++++++++++ .../references/transactions-sql.md | 49 +++++++++++++++++ .../references/versioned-features.md | 28 ++++++++++ 5 files changed, 202 insertions(+) create mode 100644 skills/firebird-driver-python/SKILL.md create mode 100644 skills/firebird-driver-python/references/connections-resources.md create mode 100644 skills/firebird-driver-python/references/transactions-sql.md create mode 100644 skills/firebird-driver-python/references/versioned-features.md diff --git a/README.md b/README.md index 77b48ef..659a57a 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ enhancements for convenient use of Firebird RDBMS. **Table of Contents** - [Installation](#installation) +- [Agent skill](#agent-skill) - [License](#license) - [Documentation](#documentation) @@ -33,6 +34,41 @@ pip install firebird-driver See [firebird-lib](https://pypi.org/project/firebird-lib/) package for optional extensions to this driver. +## Agent skill + +This repository includes a [skill for coding with firebird-driver](skills/firebird-driver-python/SKILL.md). +Once the skill is published on GitHub, run these commands in a directory where +you want to keep a checkout (Unix-like shell): + +```sh +git clone --depth 1 --filter=blob:none --sparse https://github.com/FirebirdSQL/python3-driver.git firebird-driver-skill-source +git -C firebird-driver-skill-source sparse-checkout set skills/firebird-driver-python +``` + +Then copy the skill into the directory for each agent you use: + +```sh +# Codex +mkdir -p ~/.codex/skills +cp -R firebird-driver-skill-source/skills/firebird-driver-python ~/.codex/skills/ + +# Claude Code +mkdir -p ~/.claude/skills +cp -R firebird-driver-skill-source/skills/firebird-driver-python ~/.claude/skills/ + +# Gemini CLI +mkdir -p ~/.gemini/skills +cp -R firebird-driver-skill-source/skills/firebird-driver-python ~/.gemini/skills/ +``` + +Run only the copy commands for the agents you use. Each user-level location makes +the skill available across your projects. Codex lists installed skills with +`/skills`; Claude Code can invoke `/firebird-driver-python`; Gemini CLI lists +them with `/skills list` and can reload them with `/skills reload`. +See the [Codex](https://learn.chatgpt.com/docs/build-skills), +[Claude Code](https://code.claude.com/docs/en/skills), and +[Gemini CLI](https://geminicli.com/docs/cli/using-agent-skills/) skill guides. + ## License `firebird-driver` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html) license. diff --git a/skills/firebird-driver-python/SKILL.md b/skills/firebird-driver-python/SKILL.md new file mode 100644 index 0000000..119a6c3 --- /dev/null +++ b/skills/firebird-driver-python/SKILL.md @@ -0,0 +1,37 @@ +--- +name: firebird-driver-python +description: Generate, review, debug, and explain Python application code using the official firebird-driver package. Use for connections, SQL, transactions, events, BLOBs, configuration, and Services API; exclude legacy fdb, KInterbasDB, and unrelated generic SQL. +--- + +# Firebird driver for Python + +Use the official `firebird-driver` API for the user's **target driver version**. +Identify that version from the target project's dependency constraints or installed +package (`importlib.metadata.version("firebird-driver")`). If an exact symbol, +signature, or behavior matters, check the target package's public API and docs. +Use the published [documentation index](https://firebird-driver.rtfd.io/llms.txt) +to find the relevant usage guide or API reference in Markdown. Read its driver +version label: if the target package differs, verify exact details against its +installed code and version-matched documentation. Follow the canonical topic +links from the index. Do not import APIs from `fdb`, KInterbasDB, or unverified +generic DB-API examples. + +Read only the guidance relevant to the task: + +- [Connections and resources](references/connections-resources.md) for client + selection, configuration, connection lifetime, BLOBs, and events. +- [Transactions and SQL](references/transactions-sql.md) for transaction + boundaries, TPBs, cursors, statements, and SQL execution. +- [Versioned features and services](references/versioned-features.md) for + `*InfoProvider`, `ServerDbServices*`, and Services API calls. + +Before writing code that uses functionality selected by the **connected Firebird +server version**, establish which Firebird versions the user must support. Ask +if that is unknown; then code for the stated target without repetitive runtime +feature checks. Distinguish the Firebird server version from the Python driver +package version. + +In reviews, report invalid API calls, resource/transaction ownership defects, +and unsafe SQL separately from preferences. Verify that examples use symbols +available in the target version and that resource cleanup and commit/rollback +behavior are intentional. diff --git a/skills/firebird-driver-python/references/connections-resources.md b/skills/firebird-driver-python/references/connections-resources.md new file mode 100644 index 0000000..b31d964 --- /dev/null +++ b/skills/firebird-driver-python/references/connections-resources.md @@ -0,0 +1,52 @@ +# Connections and resource lifetime + +Use the installed Firebird client by default. Configure +`driver_config.fb_client_library.value` only when the user requires a specific +client library. In that case, set it before `connect()`, `create_database()`, +`connect_server()`, `load_api()`, or `get_api()` loads the client API. See the +[configuration guide](https://firebird-driver.rtfd.io/usage-guide/configuration/index.md) +and [database guide](https://firebird-driver.rtfd.io/usage-guide/databases/index.md). + +Prefer named database and server configurations for application connections; +keep credentials out of code when feasible. For other accepted forms, including +database names, paths, and Firebird DSNs, verify the target version's +[API reference](https://firebird-driver.rtfd.io/ref-core/index.md) +and installed code. + +Configuration attributes are option objects: assign their `.value`, rather than +replacing the option. Establish process-global `driver_config` settings during +application startup, before concurrent connection work. If a configuration +file is required, check the list of successfully read files returned by +`driver_config.read()`. + +Objects holding server resources support context managers. Prefer `with` for +`Connection`, `Server`, cursors, statements, BLOB readers, transaction managers, +distributed transaction managers, and event collectors when the lifetime fits a +clear block. If it does not, make ownership explicit and close/free the object +in reliable cleanup code. A callee receiving a caller-owned connection should +not close it unless the ownership contract says so. Likewise, a callee receiving +a caller-owned transaction manager should not commit, roll back, or close it +without an explicit ownership contract. Obtain attached resource objects +through driver factories or their owners rather than constructing them +directly. Close dependents before their owner and do not use them after the +owner closes. + +Resource context managers release resources; they do not all define the same +transaction outcome. In particular, a connection closing with an active +transaction rolls it back, while the [`transaction()` context manager](transactions-sql.md) +provides commit on success and rollback on error. Never rely on `__del__` for +normal cleanup: finalization order is unpredictable, cleanup may fail, and +`ResourceWarning` may be filtered. See the +[database guide](https://firebird-driver.rtfd.io/usage-guide/databases/index.md) +for connection cleanup. + +For streamed BLOBs, keep the reader within the cursor and transaction lifetime; +close it promptly. A column may return materialized data or a `BlobReader` +depending on its size and the cursor's streaming settings. See +[BLOB handling](https://firebird-driver.rtfd.io/usage-guide/data-handling-and-conversions/index.md). + +Treat [events](https://firebird-driver.rtfd.io/usage-guide/database-events/index.md) as wake-up +signals, not durable messages. A posted event is observable after the posting +transaction commits; notifications contain occurrence counts, not payloads. +Query durable database state to learn what changed. An event collector's context +calls `begin()` and `close()`; outside a context, do both explicitly. diff --git a/skills/firebird-driver-python/references/transactions-sql.md b/skills/firebird-driver-python/references/transactions-sql.md new file mode 100644 index 0000000..3727f35 --- /dev/null +++ b/skills/firebird-driver-python/references/transactions-sql.md @@ -0,0 +1,49 @@ +# Transactions and SQL + +Manage transactions explicitly. Prefer `transaction()` when the work fits a +context: it begins on entry, commits on normal exit, and rolls back on error. +Use `Connection.cursor()` for the main transaction, a separate +`TransactionManager.cursor()` for that manager, and +`DistributedTransactionManager.cursor(connection)` for a distributed +transaction's member connection. A cursor belongs to one transaction manager; +do not obtain it from a different manager. See the +[transaction guide](https://firebird-driver.rtfd.io/usage-guide/transactions/index.md). + +The connection's initial `default_tpb` is a snapshot, read-write transaction +with an infinite lock wait and no TPB auto-commit. New transaction managers +inherit the connection's current default TPB; changing the connection default +does not retroactively change existing managers. Use `tpb()` for simple +isolation/access/timeout choices and `TPB` for additional parameters such as +table reservations. Supply a one-off TPB to `transaction(..., tpb=...)` or +`begin(tpb)`, or set a transaction manager's `default_tpb` for its subsequent +transactions. Verify defaults and supported isolation modes against the target +version before giving exact advice. + +```python +from firebird.driver import Isolation, TraAccessMode, connect, tpb, transaction + +read_tpb = tpb(Isolation.READ_COMMITTED_RECORD_VERSION, + access_mode=TraAccessMode.READ) +with connect("employee") as con: + with transaction(con, tpb=read_tpb): + with con.cursor() as cur: + cur.execute("select country from country where currency = ?", ("Euro",)) + rows = list(cur) +``` + +`TransactionManager.default_action` controls what happens when that manager +implicitly ends an active transaction; its default is `COMMIT`. The TPB +`auto_commit` flag is a different Firebird transaction parameter, and neither +replaces a deliberate transaction boundary. Avoid both TPB `auto_commit=True` +and auto-commit emulation by starting a new transaction for every statement, +unless the user explicitly needs that behavior. Do not assume that closing a +connection commits pending work. Review +[transaction parameters](https://firebird-driver.rtfd.io/usage-guide/transactions/index.md) +for details and check any server-version restrictions on TPB options. + +Pass data values as SQL parameters, never by string formatting or concatenation. +Use `?` placeholders with the driver's parameter API. Stream unbounded result +sets rather than fetching them all; prepare statements when reuse or metadata +inspection warrants it. `execute_immediate()` is only for statements without +results and does not accept bound parameters; use a cursor when either is +needed. See [SQL execution](https://firebird-driver.rtfd.io/usage-guide/executing-sql-statements/index.md). diff --git a/skills/firebird-driver-python/references/versioned-features.md b/skills/firebird-driver-python/references/versioned-features.md new file mode 100644 index 0000000..c7e55f4 --- /dev/null +++ b/skills/firebird-driver-python/references/versioned-features.md @@ -0,0 +1,28 @@ +# Versioned features and Services API + +The driver detects the connected Firebird version and chooses the appropriate +provider object. Examples include database, transaction, and statement +`*InfoProvider` objects and `Server.database`'s `ServerDbServices*` object. +Methods shown on a newer provider class may be absent on an object returned +for an older Firebird server. The Python package version alone cannot establish +server feature availability. + +Before writing code that calls a version-dependent provider method, ask which +Firebird server versions the code must support if that is not already clear. +Then check the method on the provider class selected for those versions and +write for the stated support range. Do not add repetitive `hasattr()` checks +before every call merely because providers are versioned. If the user needs +multiple server versions, choose a shared API or an explicit version-specific +branch where behavior genuinely differs. + +Use the [Services guide](https://firebird-driver.rtfd.io/usage-guide/working-with-services/index.md) +for administrative work and the [Core API reference](https://firebird-driver.rtfd.io/ref-core/index.md) +for exact provider methods. Services API objects have their own ownership and +lifetimes; use `Server` as a context manager where practical. Do not assume a +SQL `Connection` or cursor method performs a Services API operation. + +Paths supplied to backup, restore, and maintenance services are interpreted by +the Firebird server, which may run on a different host from the Python process. +Some service actions produce output or continue after the initiating call; +follow the method's completion and output contract, using `Server` output +methods or `wait()` as appropriate before treating the action as finished. From 8cab5db63f98784be06d0d69d9b5328ae929f206 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Fri, 9 Oct 2026 11:20:10 +0200 Subject: [PATCH 20/48] Fix for #70 Introduced new `Server.query_timeout` atrribute with default `INFINITE_TIMEOUT` and `TIMEOUT` sentinel. It's used for all `Server` text output paths. On timeout `readline` and iteration protocol return `TIMEOUT`. Iteration is not ended on timeout. `readlines` filters out `TIMEOUT`, so its output is unchanged. --- src/firebird/driver/__init__.py | 2 +- src/firebird/driver/core.py | 75 +++++++++++++++++-------------- src/firebird/driver/types.py | 7 ++- tests/test_server.py | 80 +++++++++++++++++++++++++++++++++ 4 files changed, 129 insertions(+), 35 deletions(-) diff --git a/src/firebird/driver/__init__.py b/src/firebird/driver/__init__.py index 315b540..079d483 100644 --- a/src/firebird/driver/__init__.py +++ b/src/firebird/driver/__init__.py @@ -133,4 +133,4 @@ ) #: Current driver version, SEMVER string. -__VERSION__ = '2.0.3' +__VERSION__ = '2.0.4' diff --git a/src/firebird/driver/core.py b/src/firebird/driver/core.py index 65b238f..0c54b01 100644 --- a/src/firebird/driver/core.py +++ b/src/firebird/driver/core.py @@ -85,6 +85,7 @@ CB_OUTPUT_LINE, DESCRIPTION, FILESPEC, + TIMEOUT, BlobInfoCode, BlobType, BPBItem, @@ -208,9 +209,6 @@ 'WIN1258': 'cp1258', } -#: Sentinel that denotes timeout expiration -TIMEOUT: Sentinel = Sentinel('TIMEOUT') - # Internal #: Firebird `.iMaster` interface _master: iMaster = None @@ -231,6 +229,7 @@ isc_info_truncated = 2 isc_info_error = 3 isc_info_data_not_ready = 4 +isc_info_svc_timeout = 64 def __api_loaded(api: a.FirebirdAPI) -> None: setattr(sys.modules[__name__], '_master', api.fb_get_master_interface()) # noqa: B010 @@ -5606,6 +5605,8 @@ def __init__(self, svc: iService, spb: bytes, host: str, encoding: str, self.host: str = host #: Service output mode (line or eof) self.mode: SrvInfoCode = SrvInfoCode.TO_EOF + #: Timeout in seconds for server output queries; -1 waits indefinitely + self.query_timeout: int = INFINITE_TIMEOUT #: Response buffer used to communicate with service self.response: CBuffer = CBuffer(USHRT_MAX) self._eof: bool = False @@ -5667,26 +5668,42 @@ def _fetch_line(self, timeout: int=INFINITE_TIMEOUT) -> str | None: # noqa: ARG0 if self.response.get_tag() != isc_info_end: # pragma: no cover raise InterfaceError("Malformed result buffer (missing isc_info_end item)") return result - def _query_output(self, timeout: int) -> str: + def _query_output(self, timeout: int) -> str | Sentinel: self.response.clear() self._svc.query(self._make_request(timeout), bytes([self.mode]), self.response.raw) - if (tag := self.response.get_tag()) != self.mode: # pragma: no cover + if (tag := self.response.get_tag()) == isc_info_svc_timeout: + return TIMEOUT + if tag != self.mode: # pragma: no cover raise InterfaceError(f"Service responded with error code: {tag}") return self.response.read_sized_string(encoding=self.encoding, errors=self.encoding_errors) - def _read_output(self, *, init: str='', timeout: int=INFINITE_TIMEOUT) -> None: - data = self._query_output(timeout) + def _read_output(self, *, init: str='') -> bool: + """Fetch output into the line buffer; return True if the query timed out.""" + data = self._query_output(self.query_timeout) + if data is TIMEOUT: + self.__line_buffer = init.splitlines(keepends=True) + return True + tag = self.response.get_tag() + timed_out = tag == isc_info_svc_timeout if self.mode is SrvInfoCode.TO_EOF: - self._eof = self.response.get_tag() == isc_info_end + self._eof = tag == isc_info_end else: # LINE mode - self._eof = not data - while (tag := self.response.get_tag()) == isc_info_truncated: - data += self._query_output(timeout) - if tag != isc_info_end: # pragma: no cover + while tag == isc_info_truncated: + part = self._query_output(self.query_timeout) + if part is TIMEOUT: + timed_out = True + break + data += part + tag = self.response.get_tag() + timed_out = tag == isc_info_svc_timeout + if not timed_out and tag != isc_info_end: # pragma: no cover raise InterfaceError("Malformed result buffer (missing isc_info_end item)") + if not timed_out: + self._eof = not data init += data - if data and self.mode is SrvInfoCode.LINE: + if data and self.mode is SrvInfoCode.LINE and not timed_out: init += '\n' self.__line_buffer = init.splitlines(keepends=True) + return timed_out def _read_all_binary_output(self, *, timeout: int=INFINITE_TIMEOUT) -> bytes: send = self._make_request(timeout) result = [] @@ -5740,35 +5757,27 @@ def readline_timed(self, timeout: int) -> str | Sentinel | None: if data and data.endswith('\r '): data = data[:-1] # Remove space, keep '\r' return data if data else None - def readline(self) -> str | None: + def readline(self) -> str | Sentinel | None: """Get next line of textual output from last service query. Returns: - Line of service output or `None` for EOF. + Line of service output, `.TIMEOUT` if the query timed out, or `None` for EOF. Important: - This method blocks until any output is available from server. Bacuse this method - is used by iteration over `.Server` and `.readlines` method, they will block as - well. + With the default `.query_timeout` this method blocks until output is available. """ - if self._eof and not self.__line_buffer: - return None - if not self.__line_buffer: - self._read_output() - elif len(self.__line_buffer) == 1: - line = self.__line_buffer.pop(0) + while True: + if self.__line_buffer and (self.__line_buffer[0].endswith('\n') or self._eof): + return self.__line_buffer.pop(0) if self._eof: - return line - self._read_output(init=line) - while not self.__line_buffer[0].endswith('\n'): - self._read_output(init=self.__line_buffer.pop(0)) - if self.__line_buffer: - return self.__line_buffer.pop(0) - return None + return None + pending = self.__line_buffer.pop(0) if self.__line_buffer else '' + if self._read_output(init=pending): + return TIMEOUT def readlines(self) -> list[str]: - """Get list of remaining output lines from last service query. + """Get remaining output lines, omitting any timeout signals. """ - return list(self) + return [line for line in self if line is not TIMEOUT] def wait(self) -> None: """Wait until running service completes, i.e. stops sending data. """ diff --git a/src/firebird/driver/types.py b/src/firebird/driver/types.py index 64deff8..2e742c5 100644 --- a/src/firebird/driver/types.py +++ b/src/firebird/driver/types.py @@ -52,7 +52,7 @@ from dateutil import tz -from firebird.base.types import Error +from firebird.base.types import Error, Sentinel # Exceptions required by Python Database API 2.0 @@ -156,6 +156,11 @@ def __init__(self, *args, **kwargs): def __getattr__(self, name): return None +# Sentinels + +class TIMEOUT(Sentinel): + "Sentinel to signal that operation timed out" + # Enums class NetProtocol(IntEnum): diff --git a/tests/test_server.py b/tests/test_server.py index 7a28f0b..900a336 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -23,6 +23,7 @@ # See LICENSE.TXT for details. import inspect +from ctypes import memmove from io import BytesIO import pytest from packaging.specifiers import SpecifierSet @@ -154,6 +155,85 @@ def test_output_to_eof(server_connection): server_connection.mode = SrvInfoCode.TO_EOF test_log(server_connection) + +class OutputService: + """Feed service query response buffers without depending on server timing.""" + def __init__(self, responses): + self.responses = iter(responses) + self.requests = [] + + def query(self, send, request, output): + self.requests.append((send, request)) + response = next(self.responses) + memmove(output, response, len(response)) + + def detach(self): + pass + + +def output_response(mode, data='', tag=1): + encoded = data.encode('utf8') + return bytes([mode]) + len(encoded).to_bytes(2, 'little') + encoded + bytes([tag]) + + +@pytest.mark.parametrize('mode', [SrvInfoCode.LINE, SrvInfoCode.TO_EOF]) +@pytest.mark.parametrize('timeout', [-1, 1]) +@pytest.mark.parametrize('consumer', ['readline', 'iteration', 'readlines']) +def test_text_output_modes_and_timeouts(mode, timeout, consumer): + responses = [] + if timeout > 0: + responses.append(bytes([SrvInfoCode.TIMEOUT])) + if mode is SrvInfoCode.LINE: + responses.append(output_response(mode, 'first')) + if timeout > 0: + responses.append(bytes([SrvInfoCode.TIMEOUT])) + responses.extend([output_response(mode, 'second'), output_response(mode)]) + else: + responses.append(output_response(mode, 'first\n', 2)) + if timeout > 0: + responses.append(bytes([SrvInfoCode.TIMEOUT])) + responses.extend([output_response(mode, 'second\n', 2), output_response(mode)]) + service = OutputService(responses) + server = driver.Server(service, b'', 'localhost', 'utf8', 'strict') + server.mode = mode + server.query_timeout = timeout + try: + expected = ['first\n', 'second\n'] + if consumer == 'readline': + result = [server.readline() for _ in range(len(expected) + 2 * (timeout > 0))] + assert server.readline() is None + elif consumer == 'iteration': + result = list(server) + else: + result = server.readlines() + if timeout > 0 and consumer != 'readlines': + expected = [driver.TIMEOUT, expected[0], driver.TIMEOUT, expected[1]] + assert result == expected + expected_send = None if timeout < 0 else bytes([SrvInfoCode.TIMEOUT, 2, 0, timeout, 0]) + assert all(send == expected_send and request == bytes([mode]) + for send, request in service.requests) + finally: + server.close() + + +@pytest.mark.parametrize('mode', [SrvInfoCode.LINE, SrvInfoCode.TO_EOF]) +def test_text_output_timeout_preserves_partial_line(mode): + if mode is SrvInfoCode.LINE: + responses = [output_response(mode, 'part', 2), bytes([SrvInfoCode.TIMEOUT]), + output_response(mode, 'ial'), output_response(mode)] + else: + responses = [output_response(mode, 'part', SrvInfoCode.TIMEOUT), + output_response(mode, 'ial\n'), output_response(mode)] + server = driver.Server(OutputService(responses), b'', 'localhost', 'utf8', 'strict') + server.mode = mode + server.query_timeout = 1 + try: + assert server.readline() is driver.TIMEOUT + assert server.readline() == 'partial\n' + assert server.readline() is None + finally: + server.close() + def test_get_limbo_transaction_ids(server_connection, db_file): pytest.skip('Not implemented yet') ids = server_connection.database.get_limbo_transaction_ids(database=str(db_file)) From 8c7c4b85d2945d019466f3014986e876e3c24f25 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Fri, 9 Oct 2026 11:20:52 +0200 Subject: [PATCH 21/48] Add TIMEOUT to firebird.driver API --- src/firebird/driver/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/firebird/driver/__init__.py b/src/firebird/driver/__init__.py index 079d483..ca29457 100644 --- a/src/firebird/driver/__init__.py +++ b/src/firebird/driver/__init__.py @@ -130,6 +130,7 @@ get_timezone, paramstyle, threadsafety, + TINEOUT, ) #: Current driver version, SEMVER string. From 5d2588481e4b765f21c649eff451d8edcdb61e82 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Fri, 9 Oct 2026 11:28:18 +0200 Subject: [PATCH 22/48] Fix typo --- src/firebird/driver/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/firebird/driver/__init__.py b/src/firebird/driver/__init__.py index ca29457..7888dd3 100644 --- a/src/firebird/driver/__init__.py +++ b/src/firebird/driver/__init__.py @@ -130,7 +130,7 @@ get_timezone, paramstyle, threadsafety, - TINEOUT, + TIMEOUT, ) #: Current driver version, SEMVER string. From e95ca8c9cd8cc9cdf2b395044c588e54790c3c37 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Fri, 9 Oct 2026 11:29:19 +0200 Subject: [PATCH 23/48] Updated changelog --- CHANGELOG.md | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 51640ab..dec3f3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,31 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## Development + +### Added + +- Firebird 6 trace session plugin support: `ServerTraceServices.start()` accepts plugin names, + and `TraceSession` reports the plugins returned by the service manager. +- Configurable `Server.query_timeout` and a `TIMEOUT` sentinel for timed text output queries. + `readline()` and iteration report timeouts without ending output; `readlines()` omits them. +- Generated `llms.txt` for the published documentation and a repository skill for coding with + `firebird-driver`. +- Developer guidance in `development/`, including module notes and test and build instructions. + +### Changed + +- Migrated the user documentation and Read the Docs build from Sphinx to Zensical, including + the API reference and docset workflow. +- Split the usage guide into topic pages and corrected examples, links, and API descriptions. +- Updated repository funding information and removed the unused `gdocs` build environment. + +### Fixed + +- GH-69: Avoid detaching an already released Firebird 5 attachment during garbage collection. +- Keep the trace session `plugins` argument optional for existing callers. +- Correct historical changelog issue references and links for Markdown rendering in Zensical. + ## [2.0.3] - 2026-04-20 ### Fixed @@ -25,7 +50,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed -- #48: AttributeError object has no attribute 'logging_id' in "__del__" methods +- GH-48: AttributeError object has no attribute 'logging_id' in "__del__" methods ## [2.0.0] - 2025-04-30 @@ -157,8 +182,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed -- #27 - Failed to establish a connection to the server on the specified port. -- #15 - Documentation issue. +- GH-27 - Failed to establish a connection to the server on the specified port. +- GH-15 - Documentation issue. - Fixed issue on MacOS (see GH-7827 in Firebird) ### Changed From 2f405db907addc20cee8abfcc0a35415d245948b Mon Sep 17 00:00:00 2001 From: "F.D.Castel" Date: Sat, 10 Oct 2026 00:01:35 -0300 Subject: [PATCH 24/48] Fix Server.readline() dropping buffered lines after a non-LF line boundary readline() treated any buffered piece not ending in '\n' as an incomplete line and re-read it via _read_output(init=...), which replaces the whole line buffer. str.splitlines() also breaks on CR, FF and other non-LF separators, so a bare CR inside SQL text in trace output discarded every line buffered after it. Only the last buffered piece can be incomplete. Refs #70. --- src/firebird/driver/core.py | 5 ++++- tests/test_server.py | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/firebird/driver/core.py b/src/firebird/driver/core.py index 0c54b01..e7c6dec 100644 --- a/src/firebird/driver/core.py +++ b/src/firebird/driver/core.py @@ -5767,7 +5767,10 @@ def readline(self) -> str | Sentinel | None: With the default `.query_timeout` this method blocks until output is available. """ while True: - if self.__line_buffer and (self.__line_buffer[0].endswith('\n') or self._eof): + # Only the last buffered piece can be an incomplete line; earlier ones ended on + # another `splitlines()` boundary (e.g. a bare '\r' inside SQL text). + if self.__line_buffer and (len(self.__line_buffer) > 1 + or self.__line_buffer[0].endswith('\n') or self._eof): return self.__line_buffer.pop(0) if self._eof: return None diff --git a/tests/test_server.py b/tests/test_server.py index 900a336..34a2aac 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -234,6 +234,21 @@ def test_text_output_timeout_preserves_partial_line(mode): finally: server.close() +@pytest.mark.parametrize('timeout', [-1, 1]) +def test_text_output_non_lf_line_boundary_keeps_following_lines(timeout): + # str.splitlines() also breaks lines on CR, FF and other non-LF separators, which can + # occur in SQL text in trace output. Lines buffered after such a piece must survive. + responses = [output_response(SrvInfoCode.TO_EOF, 'select 1 /* a\rb */ from x\nnext\n', 2), + output_response(SrvInfoCode.TO_EOF, 'last\n', 2), + output_response(SrvInfoCode.TO_EOF)] + server = driver.Server(OutputService(responses), b'', 'localhost', 'utf8', 'strict') + server.mode = SrvInfoCode.TO_EOF + server.query_timeout = timeout + try: + assert ''.join(server.readlines()) == 'select 1 /* a\rb */ from x\nnext\nlast\n' + finally: + server.close() + def test_get_limbo_transaction_ids(server_connection, db_file): pytest.skip('Not implemented yet') ids = server_connection.database.get_limbo_transaction_ids(database=str(db_file)) From cec82dd8e183b90d7874e4121691f6011b3b0ba3 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Sat, 10 Oct 2026 15:22:44 +0200 Subject: [PATCH 25/48] Fix rendering of attributes in documentation --- docs/zensical.toml | 2 + src/firebird/driver/__init__.py | 2 +- src/firebird/driver/config.py | 92 +++++++++++++------------- src/firebird/driver/core.py | 104 ++++++++++++++---------------- src/firebird/driver/fbapi.py | 56 ++++++++-------- src/firebird/driver/hooks.py | 14 ++-- src/firebird/driver/interfaces.py | 2 +- src/firebird/driver/types.py | 40 ++++++------ 8 files changed, 154 insertions(+), 158 deletions(-) diff --git a/docs/zensical.toml b/docs/zensical.toml index 6ab57e9..11d29ae 100644 --- a/docs/zensical.toml +++ b/docs/zensical.toml @@ -52,7 +52,9 @@ inventories = ["https://docs.python.org/3/objects.inv"] [project.plugins.mkdocstrings.handlers.python.options] docstring_style = "google" inherited_members = true +show_attribute_values = false show_root_heading = true +show_signature_annotations = true show_source = true [project.plugins.llmstxt] diff --git a/src/firebird/driver/__init__.py b/src/firebird/driver/__init__.py index 7888dd3..f863814 100644 --- a/src/firebird/driver/__init__.py +++ b/src/firebird/driver/__init__.py @@ -133,5 +133,5 @@ TIMEOUT, ) -#: Current driver version, SEMVER string. __VERSION__ = '2.0.4' +"Current driver version, SEMVER string." diff --git a/src/firebird/driver/config.py b/src/firebird/driver/config.py index 7848eb7..91a248a 100644 --- a/src/firebird/driver/config.py +++ b/src/firebird/driver/config.py @@ -70,134 +70,134 @@ class ServerConfig(Config): """ def __init__(self, name: str, *, optional: bool=False, description: str | None=None): super().__init__(name, optional=optional, description=description) - #: Server host machine specification self.host: StrOption = \ StrOption('host', "Server host machine specification") - #: Port used by Firebird server + "Server host machine specification" self.port: StrOption = \ StrOption('port', "Port used by Firebird server") - #: Defaul user name, default is envar ISC_USER or None if not specified + "Port used by Firebird server" self.user: StrOption = \ StrOption('user', "Defaul user name", default=os.environ.get('ISC_USER', None)) - #: Default user password, default is envar ISC_PASSWORD or None if not specified + "Defaul user name, default is envar ISC_USER or None if not specified" self.password: StrOption = \ StrOption('password', "Default user password", default=os.environ.get('ISC_PASSWORD', None)) - #: Configuration override + "Default user password, default is envar ISC_PASSWORD or None if not specified" self.config: StrOption = \ StrOption('config', "Configuration override") - #: List of authentication plugins override + "Configuration override" self.auth_plugin_list: StrOption = \ StrOption('auth_plugin_list', "List of authentication plugins override") - #: Use trusted authentication, default: False + "List of authentication plugins override" self.trusted_auth: BoolOption = \ BoolOption('trusted_auth', "Use trusted authentication", default=False) - #: Encoding used for text data exchange with server + "Use trusted authentication, default: False" self.encoding: StrOption = \ StrOption('encoding', "Encoding used for text data exchange with server", default='ascii') - #: Handler used for encoding errors. See `codecs error handlers ` for details. + "Encoding used for text data exchange with server" self.encoding_errors: StrOption = \ StrOption('encoding_errors', "Handler used for encoding errors", default='strict') + "Handler used for encoding errors. See `codecs error handlers ` for details." class DatabaseConfig(Config): """Represents configuration options specific to a named Firebird database entry, including connection and creation parameters. """ def __init__(self, name: str, *, optional: bool=False, description: str | None=None): super().__init__(name, optional=optional, description=description) - #: Name of server where database is located self.server: StrOption = \ StrOption('server', "Name of server where database is located") - #: Database connection string + "Name of server where database is located" self.dsn: StrOption = \ StrOption('dsn', "Database connection string") - #: Database file specification or alias + "Database connection string" self.database: StrOption = \ StrOption('database', "Database file specification or alias") - #: Specifies whether the database parameter (filename) is encoded in UTF-8 when passed to the server. + "Database file specification or alias" self.utf8filename: BoolOption = \ BoolOption('utf8filename', "Specifies whether the database parameter (filename) is encoded in UTF-8 when passed to the server.") - #: Network protocol to use for the connection. Value must be a member of the .NetProtocol enum. + "Specifies whether the database parameter (filename) is encoded in UTF-8 when passed to the server." self.protocol: EnumOption = \ EnumOption('protocol', NetProtocol, "Network protocol to use for the connection. Value must be a member of the .NetProtocol enum.") - #: Defaul user name, default is envar ISC_USER or None if not specified + "Network protocol to use for the connection. Value must be a member of the .NetProtocol enum." self.user: StrOption = \ StrOption('user', "Defaul user name", default=os.environ.get('ISC_USER', None)) - #: Default user password, default is envar ISC_PASSWORD or None if not specified + "Defaul user name, default is envar ISC_USER or None if not specified" self.password: StrOption = \ StrOption('password', "Default user password", default=os.environ.get('ISC_PASSWORD', None)) - #: Use trusted authentication, default: False + "Default user password, default is envar ISC_PASSWORD or None if not specified" self.trusted_auth: BoolOption = \ BoolOption('trusted_auth', "Use trusted authentication", default=False) - #: User role + "Use trusted authentication, default: False" self.role: StrOption = \ StrOption('role', "User role") - #: Character set for database connection + "User role" self.charset: StrOption = \ StrOption('charset', "Character set for database connection") - #: SQL Dialect for database connection, default: 3 + "Character set for database connection" self.sql_dialect: IntOption = \ IntOption('sql_dialect', "SQL Dialect for database connection", default=3) - #: Connection timeout + "SQL Dialect for database connection, default: 3" self.timeout: IntOption = \ IntOption('timeout', "Connection timeout") - #: Do not use linger for database connection + "Connection timeout" self.no_linger: BoolOption = \ BoolOption('no_linger', "Do not use linger for database connection") - #: Page cache size override for database connection + "Do not use linger for database connection" self.cache_size: IntOption = \ IntOption('cache_size', "Page cache size override for database connection") - #: Dummy packet interval for this database connection + "Page cache size override for database connection" self.dummy_packet_interval: IntOption = \ IntOption('dummy_packet_interval', "Dummy packet interval") - #: Configuration override + "Dummy packet interval for this database connection" self.config: StrOption = \ StrOption('config', "Configuration override") - #: List of authentication plugins override + "Configuration override" self.auth_plugin_list: StrOption = \ StrOption('auth_plugin_list', "List of authentication plugins override") - #: Session time zone [Firebird 4] + "List of authentication plugins override" self.session_time_zone: StrOption = \ StrOption('session_time_zone', "Session time zone") - #: Set BIND [Firebird 4] + "Session time zone [Firebird 4]" self.set_bind: StrOption = \ StrOption('set_bind', "Set BIND - sets up columns coercion rules in session") - #: Set DECFLOAT ROUND [Firebird 4], value is `.DecfloatRound` + "Set BIND [Firebird 4]" self.decfloat_round: EnumOption = \ EnumOption('decfloat_round', DecfloatRound, "DECFLOAT round mode") - #: Specifies which DECFLOAT exceptional conditions should cause a trap (raise an error) [Firebird 4]. Accepts a list of .DecfloatTraps enum members. + "Set DECFLOAT ROUND [Firebird 4], value is `.DecfloatRound`" self.decfloat_traps: ListOption = \ ListOption('decfloat_traps', DecfloatTraps, """Specifies which DECFLOAT exceptional conditions should cause a trap (raise an error) [Firebird 4]. Accepts a list of .DecfloatTraps enum members.""") - #: Number of parallel workers + "Specifies which DECFLOAT exceptional conditions should cause a trap (raise an error) [Firebird 4]. Accepts a list of .DecfloatTraps enum members." self.parallel_workers = \ IntOption('parallel_workers', "Number of parallel workers") + "Number of parallel workers" # --- Options specific to Database Creation --- - #: Database create option. Page size to be used. self.page_size: IntOption = \ IntOption('page_size', "Page size to be used for created database.") - #: Database create option. Write mode (True = sync/False = async). + "Database create option. Page size to be used." self.forced_writes: BoolOption = \ BoolOption('forced_writes', "Write mode for created database (True = sync, False = async)") - #: Database create option. Character set for the database. + "Database create option. Write mode (True = sync/False = async)." self.db_charset: StrOption = \ StrOption('db_charset', "Character set for created database") - #: Database create option. SQL dialect for the database. + "Database create option. Character set for the database." self.db_sql_dialect: IntOption = \ IntOption('db_sql_dialect', "SQL dialect for created database") - #: Database create option. Page cache size override for database. + "Database create option. SQL dialect for the database." self.db_cache_size: IntOption = \ IntOption('db_cache_size', "Page cache size override for created database") - #: Database create option. Sweep interval for the database. + "Database create option. Page cache size override for database." self.sweep_interval: IntOption = \ IntOption('sweep_interval', "Sweep interval for created database") - #: Database create option. Data page space usage (True = reserve space, False = Use all space). + "Database create option. Sweep interval for the database." self.reserve_space: BoolOption = \ BoolOption('reserve_space', "Data page space usage for created database (True = reserve space, False = Use all space)") + "Database create option. Data page space usage (True = reserve space, False = Use all space)." class DriverConfig(Config): """Main configuration object for the Firebird driver. Holds global settings, default @@ -209,28 +209,28 @@ class DriverConfig(Config): """ def __init__(self, name: str): super().__init__(name) - #: Path to Firebird client library self.fb_client_library: StrOption = \ StrOption('fb_client_library', "Path to Firebird client library") - #: BLOB size threshold. Bigger BLOB will be returned as stream BLOBs. + "Path to Firebird client library" self.stream_blob_threshold: IntOption = \ IntOption('stream_blob_threshold', "BLOB size threshold. Bigger BLOB will be returned as stream BLOBs.", default=65536) - #: Default database configuration ('firebird.db.defaults') + "BLOB size threshold. Bigger BLOB will be returned as stream BLOBs." self.db_defaults: DatabaseConfig = DatabaseConfig('firebird.db.defaults', optional=True, description="Default database configuration.") - #: Default server configuration ('firebird.server.defaults') + "Default database configuration ('firebird.db.defaults')" self.server_defaults: ServerConfig = ServerConfig('firebird.server.defaults', optional=True, description="Default server configuration.") - #: Registered servers + "Default server configuration ('firebird.server.defaults')" self.servers: ConfigListOption = \ ConfigListOption('servers', ServerConfig, "Registered servers") - #: Registered databases + "Registered servers" self.databases: ConfigListOption = \ ConfigListOption('databases', DatabaseConfig, "Registered databases") + "Registered databases" def read(self, filenames: str | Iterable, encoding: str | None=None): """Read configuration from a filename or an iterable of filenames. @@ -336,7 +336,5 @@ def register_database(self, name: str, config: str | None=None) -> DatabaseConfi # Configuration -#: Global driver configuration instance. -#: Load settings from files/strings/dicts into this object before connecting, -#: or modify its attributes directly for programmatic configuration. driver_config: DriverConfig = DriverConfig('firebird.driver') +"Global driver configuration instance.\nLoad settings from files/strings/dicts into this object before connecting,\nor modify its attributes directly for programmatic configuration." diff --git a/src/firebird/driver/core.py b/src/firebird/driver/core.py index e7c6dec..0b0c79b 100644 --- a/src/firebird/driver/core.py +++ b/src/firebird/driver/core.py @@ -181,13 +181,12 @@ FB40: float = 4.0 INFINITE_TIMEOUT: int = -1 -#: Max BLOB segment size MAX_BLOB_SEGMENT_SIZE = 65535 +"Max BLOB segment size" -#: Current filesystem encoding FS_ENCODING = sys.getfilesystemencoding() +"Current filesystem encoding" -#: Python dictionary that maps Firebird character set names (key) to Python character sets (value). CHARSET_MAP = {None: a.getpreferredencoding(), 'NONE': a.getpreferredencoding(), 'OCTETS': None, 'UNICODE_FSS': 'utf_8', 'UTF8': 'utf_8', 'UTF-8': 'utf_8', 'ASCII': 'ascii', 'SJIS_0208': 'shift_jis', 'EUCJ_0208': 'euc_jp', @@ -208,12 +207,13 @@ 'GBK': 'gbk', 'KOI8R': 'koi8_r', 'KOI8U': 'koi8_u', 'WIN1258': 'cp1258', } +"Python dictionary that maps Firebird character set names (key) to Python character sets (value)." # Internal -#: Firebird `.iMaster` interface _master: iMaster = None -#: Firebird `.iUtil` interface +"Firebird `.iMaster` interface" _util: iUtil = None +"Firebird `.iUtil` interface" _thns = threading.local() _ten_to = [10 ** x for x in range(30)] @@ -521,73 +521,73 @@ def __init__(self, *, user: str | None=None, password: str | None=None, role: st # AuthClient, WireCryptPlugin, Providers, ConnectionTimeout, WireCrypt, # WireCompression, DummyPacketInterval, RemoteServiceName, RemoteServicePort, # RemoteAuxPort, TcpNoNagle, IpcName, RemotePipeName, ClientBatchBuffer [FB4+] - #: Configuration override self.config: str | None = config - #: List of authentication plugins override + "Configuration override" self.auth_plugin_list: str | None = auth_plugin_list + "List of authentication plugins override" # Connect - #: Use trusted authentication self.trusted_auth: bool = trusted_auth - #: User name + "Use trusted authentication" self.user: str | None = user - #: User password + "User name" self.password: str | None = password - #: User role + "User password" self.role: str | None = role - #: SQL Dialect for database connection + "User role" self.sql_dialect: int = sql_dialect - #: Character set for database connection + "SQL Dialect for database connection" self.charset: str = charset - #: Connection timeout + "Character set for database connection" self.timeout: int | None = timeout - #: Dummy packet interval for this database connection + "Connection timeout" self.dummy_packet_interval: int | None = dummy_packet_interval - #: Page cache size override for database connection + "Dummy packet interval for this database connection" self.cache_size: int | None = cache_size - #: Disable garbage collection for database connection + "Page cache size override for database connection" self.no_gc: bool = no_gc - #: Disable database triggers for database connection + "Disable garbage collection for database connection" self.no_db_triggers: bool = no_db_triggers - #: Do not use linger for database connection + "Disable database triggers for database connection" self.no_linger: bool = no_linger - #: Database filename passed in UTF8 + "Do not use linger for database connection" self.utf8filename: bool = utf8filename - #: Scope for RDB$DB_KEY values + "Database filename passed in UTF8" self.dbkey_scope: DBKeyScope | None = dbkey_scope - #: Session time zone [Firebird 4] + "Scope for RDB$DB_KEY values" self.session_time_zone: str | None = session_time_zone - #: Set replica mode [Firebird 4] + "Session time zone [Firebird 4]" self.set_db_replica: ReplicaMode | None = set_db_replica - #: Set BIND [Firebird 4] + "Set replica mode [Firebird 4]" self.set_bind: str | None = set_bind - #: Set DECFLOAT ROUND [Firebird 4] + "Set BIND [Firebird 4]" self.decfloat_round: DecfloatRound | None = decfloat_round - #: Set DECFLOAT TRAPS [Firebird 4] + "Set DECFLOAT ROUND [Firebird 4]" self.decfloat_traps: list[DecfloatTraps] | None = \ None if decfloat_traps is None else list(decfloat_traps) + "Set DECFLOAT TRAPS [Firebird 4]" # For db create - #: Database page size [db create only] self.page_size: int | None = page_size - #: Overwrite existing database [db create only] + "Database page size [db create only]" self.overwrite: bool = overwrite - #: Number of pages in database cache [db create only] + "Overwrite existing database [db create only]" self.db_buffers: int | None= None - #: Database cache size [db create only] + "Number of pages in database cache [db create only]" self.db_cache_size: int | None = db_cache_size - #: Database write mode (True = sync/False = async) [db create only] + "Database cache size [db create only]" self.forced_writes: bool | None = forced_writes - #: Database data page space usage (True = reserve space, False = Use all space) [db create only] + "Database write mode (True = sync/False = async) [db create only]" self.reserve_space: bool | None = reserve_space - #: Database access mode (True = read-only/False = read-write) [db create only] + "Database data page space usage (True = reserve space, False = Use all space) [db create only]" self.read_only: bool = read_only - #: Sweep interval for the database [db create only] + "Database access mode (True = read-only/False = read-write) [db create only]" self.sweep_interval: int | None = sweep_interval - #: SQL dialect for the database [db create only] + "Sweep interval for the database [db create only]" self.db_sql_dialect: int | None = db_sql_dialect - #: Character set for the database [db create only] + "SQL dialect for the database [db create only]" self.db_charset: str | None = db_charset - #: Number of parallel workers + "Character set for the database [db create only]" self.parallel_workers: int | None = parallel_workers + "Number of parallel workers" def clear(self) -> None: """Clear all information. """ @@ -1772,8 +1772,8 @@ def __init__(self, att: iAttachment, dsn: str, dpb: bytes | None=None, sql_diale self._encoding: str = CHARSET_MAP.get(charset, 'ascii') self._att.encoding = self._encoding self._dpb: bytes | None = dpb - #: Default TPB for newly created transaction managers self.default_tpb: bytes = tpb(Isolation.SNAPSHOT) + "Default TPB for newly created transaction managers" self._transactions: list[TransactionManager] = [] self._statements: list[Statement] = [] # @@ -2590,10 +2590,10 @@ class TransactionManager: def __init__(self, connection: Connection, default_tpb: bytes, default_action: DefaultAction=DefaultAction.COMMIT): self._connection: Callable[[], Connection] = weakref.ref(connection, self.__dead_con) - #: Default Transaction Parameter Block used to start transaction self.default_tpb: bytes = default_tpb - #: Default action (commit/rollback) to be performed when transaction is closed. + "Default Transaction Parameter Block used to start transaction" self.default_action: DefaultAction = default_action + "Default action (commit/rollback) to be performed when transaction is closed." self.__handle: a.FB_API_HANDLE = None self.__info: TransactionInfoProvider | TransactionInfoProvider3 = None self._cursors: list = [] # Weak references to cursors @@ -3326,11 +3326,8 @@ class Cursor: Note: Implements context manager protocol to call `.close()` automatically. """ - #: This read/write attribute specifies the number of rows to fetch at a time with - #: .fetchmany(). It defaults to 1 meaning to fetch a single row at a time. - #: - #: Required by Python DB API 2.0 arraysize: int = 1 + "This read/write attribute specifies the number of rows to fetch at a time with\n.fetchmany(). It defaults to 1 meaning to fetch a single row at a time.\n\nRequired by Python DB API 2.0" def __init__(self, connection: Connection, transaction: TransactionManager): self._connection: Connection = connection self._dialect: int = connection.sql_dialect @@ -3345,11 +3342,10 @@ def __init__(self, connection: Connection, transaction: TransactionManager): self.__output_cache: tuple = None self.__internal: bool = False self.__blob_readers: set = weakref.WeakSet() - #: Names of columns that should be returned as `BlobReader`. self.stream_blobs: list[str] = [] - #: BLOBs greater than threshold are returned as `BlobReader` instead in materialized form. - #: Defaults to the value from `driver_config`. + "Names of columns that should be returned as `BlobReader`." self.stream_blob_threshold = driver_config.stream_blob_threshold.value + "BLOBs greater than threshold are returned as `BlobReader` instead in materialized form.\nDefaults to the value from `driver_config`." def __enter__(self) -> Self: return self def __exit__(self, exc_type, exc_value, traceback) -> None: @@ -5599,22 +5595,22 @@ class Server: def __init__(self, svc: iService, spb: bytes, host: str, encoding: str, encoding_errors: str): self._svc: iService = svc - #: Service Parameter Buffer (SPB) used to connect the service manager self.spb: bytes = spb - #: Server host + "Service Parameter Buffer (SPB) used to connect the service manager" self.host: str = host - #: Service output mode (line or eof) + "Server host" self.mode: SrvInfoCode = SrvInfoCode.TO_EOF - #: Timeout in seconds for server output queries; -1 waits indefinitely + "Service output mode (line or eof)" self.query_timeout: int = INFINITE_TIMEOUT - #: Response buffer used to communicate with service + "Timeout in seconds for server output queries; -1 waits indefinitely" self.response: CBuffer = CBuffer(USHRT_MAX) + "Response buffer used to communicate with service" self._eof: bool = False self.__line_buffer: list[str] = [] - #: Encoding used for text data exchange with server self.encoding: str = encoding - #: Handler used for encoding errors. See: `codecs#error-handlers` + "Encoding used for text data exchange with server" self.encoding_errors: str = encoding_errors + "Handler used for encoding errors. See: `codecs#error-handlers`" # self.__ev: float = None self.__info: ServerInfoProvider = None diff --git a/src/firebird/driver/fbapi.py b/src/firebird/driver/fbapi.py index 0297915..2880d81 100644 --- a/src/firebird/driver/fbapi.py +++ b/src/firebird/driver/fbapi.py @@ -1891,8 +1891,8 @@ class IInt128_struct(Structure): ('fromString', IInt128_fromString)] -#: Encoding used to decode error messages from Firebird. err_encoding = getpreferredencoding() +"Encoding used to decode error messages from Firebird." def db_api_error(status: ISC_STATUS_ARRAY) -> bool: "Returns True if `status` contains error" @@ -2072,59 +2072,59 @@ def __init__(self, filename: Path | None=None): if not file_name: raise Exception(f"Firebird Client Library '{filename}' not found") filename = file_name - #: Firebird client library self.client_library: ctypes.CDLL = None + "Firebird client library" if sys.platform in ('win32', 'cygwin', 'os2', 'os2emx'): self.client_library: ctypes.CDLL = ctypes.WinDLL(str(filename)) else: self.client_library: ctypes.CDLL = ctypes.CDLL(str(filename), mode=ctypes.RTLD_GLOBAL) - #: Firebird client library name self.client_library_name: Path = Path(filename) - #: Firebird API + "Firebird client library name" self.fb_get_master_interface = (self.client_library.fb_get_master_interface) + "Firebird API" self.fb_get_master_interface.restype = IMaster self.fb_get_master_interface.argtypes = [] - #: Firebird API self.fb_get_database_handle = self.client_library.fb_get_database_handle + "Firebird API" self.fb_get_database_handle.restype = ISC_STATUS self.fb_get_database_handle.argtypes = [ISC_STATUS_PTR, FB_API_HANDLE_PTR, IAttachment] - #: Firebird API self.fb_get_transaction_handle = (self.client_library.fb_get_transaction_handle) + "Firebird API" self.fb_get_transaction_handle.restype = ISC_STATUS self.fb_get_transaction_handle.argtypes = [ISC_STATUS_PTR, FB_API_HANDLE_PTR, ITransaction] - #: Firebird API self.fb_sqlstate = self.client_library.fb_sqlstate + "Firebird API" self.fb_sqlstate.restype = None self.fb_sqlstate.argtypes = [STRING, ISC_STATUS_PTR] - #: Firebird API self.fb_shutdown_callback = self.client_library.fb_shutdown_callback + "Firebird API" self.fb_shutdown_callback.restype = ISC_STATUS self.fb_shutdown_callback.argtypes = [ISC_STATUS_PTR, FB_SHUTDOWN_CALLBACK, c_int, c_void_p] - #: Firebird API self.isc_sqlcode = self.client_library.isc_sqlcode + "Firebird API" self.isc_sqlcode.restype = ISC_LONG self.isc_sqlcode.argtypes = [ISC_STATUS_PTR] - #: Firebird API self.fb_interpret = self.client_library.fb_interpret + "Firebird API" self.fb_interpret.restype = ISC_LONG self.fb_interpret.argtypes = [STRING, c_uint, POINTER(ISC_STATUS_PTR)] - #: Firebird API self.isc_array_lookup_bounds = (self.client_library.isc_array_lookup_bounds) + "Firebird API" self.isc_array_lookup_bounds.restype = ISC_STATUS self.isc_array_lookup_bounds.argtypes = [ISC_STATUS_PTR, FB_API_HANDLE_PTR, FB_API_HANDLE_PTR, STRING, STRING, ISC_ARRAY_DESC_PTR] - #: Firebird API self.isc_array_put_slice = self.client_library.isc_array_put_slice + "Firebird API" self.isc_array_put_slice.restype = ISC_STATUS self.isc_array_put_slice.argtypes = [ISC_STATUS_PTR, FB_API_HANDLE_PTR, FB_API_HANDLE_PTR, ISC_QUAD_PTR, ISC_ARRAY_DESC_PTR, c_void_p, ISC_LONG_PTR] - #: Firebird API self.isc_array_get_slice = self.client_library.isc_array_get_slice + "Firebird API" self.isc_array_get_slice.restype = ISC_STATUS self.isc_array_get_slice.argtypes = [ISC_STATUS_PTR, FB_API_HANDLE_PTR, FB_API_HANDLE_PTR, ISC_QUAD_PTR, @@ -2135,81 +2135,81 @@ def __init__(self, filename: Path | None=None): # C_isc_event_block(ISC_LONG, POINTER(POINTER(ISC_UCHAR)), POINTER(POINTER(ISC_UCHAR)), ISC_USHORT) self.C_isc_event_block = self.P_isc_event_block(('isc_event_block', self.client_library)) self.P_isc_event_block_args = self.C_isc_event_block.argtypes - #: Firebird API self.isc_que_events = self.client_library.isc_que_events + "Firebird API" self.isc_que_events.restype = ISC_STATUS self.isc_que_events.argtypes = [POINTER(ISC_STATUS), POINTER(FB_API_HANDLE), POINTER(ISC_LONG), c_short, POINTER(ISC_UCHAR), ISC_EVENT_CALLBACK, POINTER(ISC_UCHAR)] - #: Firebird API self.isc_event_counts = self.client_library.isc_event_counts + "Firebird API" self.isc_event_counts.restype = None self.isc_event_counts.argtypes = [POINTER(RESULT_VECTOR), c_short, POINTER(ISC_UCHAR), POINTER(ISC_UCHAR)] - #: Firebird API self.isc_cancel_events = self.client_library.isc_cancel_events + "Firebird API" self.isc_cancel_events.restype = ISC_STATUS self.isc_cancel_events.argtypes = [POINTER(ISC_STATUS), POINTER(FB_API_HANDLE), POINTER(ISC_LONG)] - #: Firebird API self.isc_compile_request = self.client_library.isc_compile_request + "Firebird API" self.isc_compile_request.restype = ISC_STATUS self.isc_compile_request.argtypes = [POINTER(ISC_STATUS), POINTER(FB_API_HANDLE), POINTER(FB_API_HANDLE), c_short, STRING] - #: Firebird API self.isc_start_request = self.client_library.isc_start_request + "Firebird API" self.isc_start_request.restype = ISC_STATUS self.isc_start_request.argtypes = [POINTER(ISC_STATUS), POINTER(FB_API_HANDLE), POINTER(FB_API_HANDLE), c_short] - #: Firebird API self.isc_release_request = self.client_library.isc_release_request + "Firebird API" self.isc_release_request.restype = ISC_STATUS self.isc_release_request.argtypes = [POINTER(ISC_STATUS), POINTER(FB_API_HANDLE)] - #: Firebird API self.isc_receive = self.client_library.isc_receive + "Firebird API" self.isc_receive.restype = ISC_STATUS self.isc_receive.argtypes = [POINTER(ISC_STATUS), POINTER(FB_API_HANDLE), c_short, c_short, c_void_p, c_short] - #: Firebird API self.isc_start_and_send = self.client_library.isc_start_and_send + "Firebird API" self.isc_start_and_send.restype = ISC_STATUS self.isc_start_and_send.argtypes = [POINTER(ISC_STATUS), POINTER(FB_API_HANDLE), POINTER(FB_API_HANDLE), c_short, c_short, c_void_p, c_short] - #: Firebird API self.isc_send = self.client_library.isc_send + "Firebird API" self.isc_send.restype = ISC_STATUS self.isc_send.argtypes = [POINTER(ISC_STATUS), POINTER(FB_API_HANDLE), c_short, c_short, c_void_p, c_short] - #: Firebird API self.isc_open_blob2 = self.client_library.isc_open_blob2 + "Firebird API" self.isc_open_blob2.restype = ISC_STATUS self.isc_open_blob2.argtypes = [POINTER(ISC_STATUS), POINTER(FB_API_HANDLE), POINTER(FB_API_HANDLE), POINTER(FB_API_HANDLE), POINTER(ISC_QUAD), ISC_USHORT, STRING] # POINTER(ISC_UCHAR) - #: Firebird API self.isc_blob_info = self.client_library.isc_blob_info + "Firebird API" self.isc_blob_info.restype = ISC_STATUS self.isc_blob_info.argtypes = [POINTER(ISC_STATUS), POINTER(FB_API_HANDLE), c_short, STRING, c_short, POINTER(c_char)] - #: Firebird API self.isc_create_blob2 = self.client_library.isc_create_blob2 + "Firebird API" self.isc_create_blob2.restype = ISC_STATUS self.isc_create_blob2.argtypes = [POINTER(ISC_STATUS), POINTER(FB_API_HANDLE), POINTER(FB_API_HANDLE), POINTER(FB_API_HANDLE), POINTER(ISC_QUAD), c_short, STRING] - #: Firebird API self.isc_get_segment = self.client_library.isc_get_segment + "Firebird API" self.isc_get_segment.restype = ISC_STATUS self.isc_get_segment.argtypes = [POINTER(ISC_STATUS), POINTER(FB_API_HANDLE), POINTER(c_ushort), c_ushort, c_void_p] - #: Firebird API self.isc_put_segment = self.client_library.isc_put_segment + "Firebird API" self.isc_put_segment.restype = ISC_STATUS self.isc_put_segment.argtypes = [POINTER(ISC_STATUS), POINTER(FB_API_HANDLE), c_ushort, c_void_p] - #: Firebird API self.isc_close_blob = self.client_library.isc_close_blob + "Firebird API" self.isc_close_blob.restype = ISC_STATUS self.isc_close_blob.argtypes = [POINTER(ISC_STATUS), POINTER(FB_API_HANDLE)] # Next netributes are set in types by API_LOADED hook diff --git a/src/firebird/driver/hooks.py b/src/firebird/driver/hooks.py index 1aa6601..6e662af 100644 --- a/src/firebird/driver/hooks.py +++ b/src/firebird/driver/hooks.py @@ -55,25 +55,25 @@ class APIHook(Enum): """Hooks related to the loading and initialization of the underlying Firebird client API. """ - #: Called after the Firebird client library has been successfully loaded and basic interfaces obtained. LOADED = auto() + "Called after the Firebird client library has been successfully loaded and basic interfaces obtained." class ConnectionHook(Enum): """Hooks related to the lifecycle of a database connection (attachment, detachment, dropping). """ - #: Called before attempting to attach to a database, allows interception or modification. ATTACH_REQUEST = auto() - #: Called after a database connection (attachment) has been successfully established. + "Called before attempting to attach to a database, allows interception or modification." ATTACHED = auto() - #: Called before attempting to detach from a database, allows cancellation. + "Called after a database connection (attachment) has been successfully established." DETACH_REQUEST = auto() - #: Called after a database connection has been successfully closed (detached). + "Called before attempting to detach from a database, allows cancellation." CLOSED = auto() - #: Called after a database has been successfully dropped. + "Called after a database connection has been successfully closed (detached)." DROPPED = auto() + "Called after a database has been successfully dropped." class ServerHook(Enum): """Hooks related to the lifecycle of a service manager connection. """ - #: Called after connecting to the Firebird service manager. ATTACHED = auto() + "Called after connecting to the Firebird service manager." diff --git a/src/firebird/driver/interfaces.py b/src/firebird/driver/interfaces.py index 494f57f..bdfe4a7 100644 --- a/src/firebird/driver/interfaces.py +++ b/src/firebird/driver/interfaces.py @@ -1098,8 +1098,8 @@ class iAttachment_v3(iReferenceCounted): VERSION = 3 def __init__(self, intf): super().__init__(intf) - #: Encoding used for string values self.encoding: str = 'ascii' + "Encoding used for string values" def get_info(self, items: bytes, buffer: bytes) -> None: "Replaces `isc_database_info()`" self.vtable.getInfo(self, self.status, len(items), items, len(buffer), buffer) diff --git a/src/firebird/driver/types.py b/src/firebird/driver/types.py index 2e742c5..3d837bc 100644 --- a/src/firebird/driver/types.py +++ b/src/firebird/driver/types.py @@ -64,12 +64,12 @@ class InterfaceError(Error): class DatabaseError(Error): """Exception raised for all errors reported by Firebird. """ - #: Returned SQLSTATE or None sqlstate: str = None - #: Returned SQLCODE or None + "Returned SQLSTATE or None" sqlcode: int = None - #: Tuple with all returned GDS error codes + "Returned SQLCODE or None" gds_codes: tuple[int] = () + "Tuple with all returned GDS error codes" class DataError(DatabaseError): """Exception raised for errors that are due to problems with the processed @@ -1419,14 +1419,14 @@ class ImpDataOld: # Constants required by Python DB API 2.0 specification -#: String constant stating the supported DB API level. apilevel: str = '2.0' -#: Integer constant stating the level of thread safety the interface supports. -#: Curretly `1` = Threads may share the module, but not connections. +"String constant stating the supported DB API level." threadsafety: int = 1 -#: String constant stating the type of parameter marker formatting expected by -#: the interface. `'qmark'` = Question mark style, e.g. '...WHERE name=?' +"""Integer constant stating the level of thread safety the interface supports. +Curretly `1` = Threads may share the module, but not connections.""" paramstyle: str = 'qmark' +"""String constant stating the type of parameter marker formatting expected by +the interface. `'qmark'` = Question mark style, e.g. '...WHERE name=?'""" # Named positional constants to be used as indices into the description # attribute of a cursor. @@ -1441,12 +1441,12 @@ class ImpDataOld: # Types Required by Python DB-API 2.0 -#: This callable constructs an object holding a date value. Date = datetime.date -#: This callable constructs an object holding a time value. +"This callable constructs an object holding a date value." Time = datetime.time -#: This callable constructs an object holding a time stamp value. +"This callable constructs an object holding a time value." Timestamp = datetime.datetime +"This callable constructs an object holding a time stamp value." def DateFromTicks(ticks: float) -> Date: # noqa: N802 """Constructs an object holding a date value from the given ticks value @@ -1466,8 +1466,8 @@ def TimestampFromTicks(ticks: float) -> Timestamp: # noqa: N802 """ return Timestamp(time.localtime(ticks)[:6]) -#: This callable constructs an object capable of holding a binary (long) string value. Binary = memoryview +"This callable constructs an object capable of holding a binary (long) string value." class DBAPITypeObject: """Python DB API 2.0 - type support. @@ -1481,25 +1481,25 @@ def __cmp__(self, other): # pragma: no cover return 1 return -1 -#: This type object is used to describe columns in a database that are string-based (e.g. CHAR). STRING = DBAPITypeObject(str) -#: This type object is used to describe (long) binary columns in a database (e.g. LONG, RAW, BLOBs). +"This type object is used to describe columns in a database that are string-based (e.g. CHAR)." BINARY = DBAPITypeObject(bytes, bytearray) -#: This type object is used to describe numeric columns in a database. +"This type object is used to describe (long) binary columns in a database (e.g. LONG, RAW, BLOBs)." NUMBER = DBAPITypeObject(int, float, decimal.Decimal) -#: This type object is used to describe date/time columns in a database. +"This type object is used to describe numeric columns in a database." DATETIME = DBAPITypeObject(datetime.datetime, datetime.date, datetime.time) -#: This type object is used to describe the "Row ID" column in a database. +"This type object is used to describe date/time columns in a database." ROWID = DBAPITypeObject() +'This type object is used to describe the "Row ID" column in a database.' # Types for type hints -#: DB API 2.0 Cursor DESCRIPTION DESCRIPTION = tuple[str, type, int, int, int, int, bool] -#: Callback that accepts line of text output +"DB API 2.0 Cursor DESCRIPTION" CB_OUTPUT_LINE = Callable[[str], None] -#: File name (incl. path) specification +"Callback that accepts line of text output" FILESPEC = str | Path +"File name (incl. path) specification" class Transactional(Protocol): # pragma: no cover """Protocol type for object that supports transactional processing.""" From dcdd94315fcade26fa40ab61597ef0de7a2912ea Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Sat, 10 Oct 2026 18:30:06 +0200 Subject: [PATCH 26/48] Introduce dark/light theme --- .gitignore | 1 + docs/zensical.toml | 12 ++++++++++++ 2 files changed, 13 insertions(+) diff --git a/.gitignore b/.gitignore index d142c1d..fa4b608 100644 --- a/.gitignore +++ b/.gitignore @@ -138,6 +138,7 @@ dmypy.json # Personal notes/ store/ +plan/ # Zensical build docs/site diff --git a/docs/zensical.toml b/docs/zensical.toml index 11d29ae..bd857fa 100644 --- a/docs/zensical.toml +++ b/docs/zensical.toml @@ -32,6 +32,16 @@ nav = [ { "License" = "license.md" }, ] +[[project.theme.palette]] +scheme = "slate" +toggle.icon = "lucide/moon" +toggle.name = "Switch to light mode" + +[[project.theme.palette]] +scheme = "default" +toggle.icon = "lucide/sun" +toggle.name = "Switch to dark mode" + [project.theme] favicon = "assets/fb-favicon.png" features = [ @@ -56,6 +66,8 @@ show_attribute_values = false show_root_heading = true show_signature_annotations = true show_source = true +backlinks = "tree" +find_stubs_package = true [project.plugins.llmstxt] enabled = true From 3f920617a9dc80d3461a36f94a0ddc441c468531 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Sat, 10 Oct 2026 18:47:02 +0200 Subject: [PATCH 27/48] Update landing page --- docs/docs/index.md | 40 +++++++++++++--------------------------- 1 file changed, 13 insertions(+), 27 deletions(-) diff --git a/docs/docs/index.md b/docs/docs/index.md index 1158915..e2a1ad8 100644 --- a/docs/docs/index.md +++ b/docs/docs/index.md @@ -11,39 +11,25 @@ This documentation set is not a tutorial on SQL or Firebird; rather, it is a top presentation of driver's feature set, with example code to demonstrate basic usage patterns. For detailed information about Firebird features, see the [Firebird documentation](http://www.firebirdsql.org/en/documentation/), and especially -the excellent [The Firebird Book](http://www.ibphoenix.com/products/books/firebird_book) +the excellent [The Firebird Book](https://www.ibphoenix.com/products/publications/fbook/) written by Helen Borrie and published by [IBPhoenix](http://www.ibphoenix.com). +!!! note + Driver development is sponsored by [IBPhoenix](http://www.ibphoenix.com). + + [![PyPI - Version](https://img.shields.io/pypi/v/firebird-driver.svg)](https://pypi.org/project/firebird-driver) + [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/firebird-driver.svg)](https://pypi.org/project/firebird-driver) + [![Hatch project](https://img.shields.io/badge/%F0%9F%A5%9A-Hatch-4051b5.svg)](https://github.com/pypa/hatch) + [![PyPI - Downloads](https://img.shields.io/pypi/dm/firebird-driver)](https://pypi.org/project/firebird-driver) + [![Libraries.io SourceRank](https://img.shields.io/librariesio/sourcerank/pypi/firebird-driver)](https://libraries.io/pypi/firebird-driver) + [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/FirebirdSQL/python3-driver) + + [Source repository](https://github.com/FirebirdSQL/python3-driver) + !!! info [firebird-lib](https://pypi.org/project/firebird-lib/) package for optional extensions to this driver. -!!! note - Requires Python 3.11+ - !!! tip You can download docset for [Dash](https://kapeli.com/dash) (MacOS) or [Zeal](https://zealdocs.org/) (Windows / Linux) documentation readers from [releases](https://github.com/FirebirdSQL/python3-driver/releases) at github. - -## Content - -- [Getting Started](getting-started.md) -- [Usage Guide](usage-guide/driver-structure.md) -- [Python Db Api Compliance](python-db-api-compliance.md) -- [Reference](ref-main.md) -- [Changelog](changelog.md) -- [License](license.md) - -Driver development is sponsored by [IBPhoenix](http://www.ibphoenix.com). - -[IBPhoenix]: http://www.ibphoenix.com -[Python]: http://python.org -[Python Database API 2.0]: http://www.python.org/dev/peps/pep-0249/ -[Firebird]: http://www.firebirdsql.org -[under]: http://www.firebirdsql.org/en/devel-python-driver/ -[Firebird Project]: http://www.firebirdsql.org -[IBPhoenix]: http://www.ibphoenix.com -[firebird-lib]: https://pypi.org/project/firebird-lib/ -[releases]: https://github.com/FirebirdSQL/python3-driver/releases -[Dash]: https://kapeli.com/dash -[Zeal]: https://zealdocs.org/ From c585b4e01a5009be7aa6f7f13f202eeea7658d98 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Sun, 11 Oct 2026 16:50:47 +0200 Subject: [PATCH 28/48] Fix for negative stream_blob_threshold; version number --- src/firebird/driver/__init__.py | 2 +- src/firebird/driver/core.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/firebird/driver/__init__.py b/src/firebird/driver/__init__.py index f863814..0c7c6a9 100644 --- a/src/firebird/driver/__init__.py +++ b/src/firebird/driver/__init__.py @@ -133,5 +133,5 @@ TIMEOUT, ) -__VERSION__ = '2.0.4' +__VERSION__ = '2.0.4.dev0' "Current driver version, SEMVER string." diff --git a/src/firebird/driver/core.py b/src/firebird/driver/core.py index 0b0c79b..f51c32d 100644 --- a/src/firebird/driver/core.py +++ b/src/firebird/driver/core.py @@ -3826,7 +3826,7 @@ def _unpack_output(self) -> tuple: segment_size = blob.get_info2(BlobInfoCode.MAX_SEGMENT) # Check if stream BLOB is requested instead materialized one if ((self.stream_blobs and (desc.alias if desc.alias != desc.field else desc.field) in self.stream_blobs) - or (blob_length > self.stream_blob_threshold)): + or (self.stream_blob_threshold != -1 and blob_length > self.stream_blob_threshold)): # Stream BLOB value = BlobReader(blob, blobid, desc.subtype, blob_length, segment_size, self._encoding, self) From c431ca5976b0b1e783fe0039c8259373e96cb95f Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Tue, 13 Oct 2026 17:11:39 +0200 Subject: [PATCH 29/48] Decode Firebird client major and minor version --- src/firebird/driver/interfaces.py | 7 ++++--- unit_tests/test_client_version.py | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) create mode 100644 unit_tests/test_client_version.py diff --git a/src/firebird/driver/interfaces.py b/src/firebird/driver/interfaces.py index bdfe4a7..3c0358c 100644 --- a/src/firebird/driver/interfaces.py +++ b/src/firebird/driver/interfaces.py @@ -1573,9 +1573,10 @@ def format_status(self, status: iStatus, encoding: str=a.err_encoding) -> str: buffer = create_string_buffer(1024) self.vtable.formatStatus(self, buffer, 1024, status) return buffer.value.decode(encoding, errors='replace') - def get_client_version(self) -> int: - "Returns integer, containing major version in byte 0 and minor version in byte 1" - return self.vtable.getClientVersion(self) + def get_client_version(self) -> tuple[int, int]: + "Returns the client library's major and minor version numbers." + version = self.vtable.getClientVersion(self) + return version >> 8, version & 0xff def get_xpb_builder(self, kind: XpbKind, buffer: bytes |None=None) -> iXpbBuilder: "Returns XpbBuilder interface." if buffer is None: diff --git a/unit_tests/test_client_version.py b/unit_tests/test_client_version.py new file mode 100644 index 0000000..73cecc9 --- /dev/null +++ b/unit_tests/test_client_version.py @@ -0,0 +1,18 @@ +"""Tests that do not require a Firebird server or client library.""" + +from types import SimpleNamespace + +import pytest + +from firebird.driver.interfaces import iUtil + + +@pytest.mark.parametrize(('encoded', 'expected'), [ + (0x0300, (3, 0)), + (0x0401, (4, 1)), + (0x0502, (5, 2)), +]) +def test_get_client_version_decodes_major_and_minor(encoded, expected): + util = SimpleNamespace(vtable=SimpleNamespace(getClientVersion=lambda _: encoded)) + + assert iUtil.get_client_version(util) == expected From 99f538c21dd5a159199fec1222047ebf2f7dc5ba Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Thu, 15 Oct 2026 12:02:18 +0200 Subject: [PATCH 30/48] Fixes and extensions - Add: A runtime provider protocol and provider-based client library selection through `load_api() - Fix: Decode `iUtil.get_client_version()` into major and minor version numbers. - Fix: tests that fail with embedded engine due t wrong test design. - Update: Documentation - Add: Python 3.15 to supported versions and test matrix --- CHANGELOG.md | 2 + development/README.md | 10 +- development/__init__.md | 1 + development/fbapi.md | 7 +- development/interfaces.md | 4 +- development/provider.md | 13 ++ docs/docs/ref-main.md | 4 + docs/docs/ref-provider.md | 7 ++ docs/docs/usage-guide/configuration.md | 18 +++ docs/docs/usage-guide/driver-structure.md | 1 + docs/zensical.toml | 4 +- pyproject.toml | 9 +- src/firebird/driver/__init__.py | 3 +- src/firebird/driver/fbapi.py | 74 ++++++----- src/firebird/driver/interfaces.py | 1 + src/firebird/driver/provider.py | 125 +++++++++++++++++++ {unit_tests => tests}/test_client_version.py | 0 tests/test_provider.py | 121 ++++++++++++++++++ tests/test_server.py | 47 +++++-- 19 files changed, 393 insertions(+), 58 deletions(-) create mode 100644 development/provider.md create mode 100644 docs/docs/ref-provider.md create mode 100644 src/firebird/driver/provider.py rename {unit_tests => tests}/test_client_version.py (100%) create mode 100644 tests/test_provider.py diff --git a/CHANGELOG.md b/CHANGELOG.md index dec3f3a..35663e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Added +- A runtime provider protocol and provider-based client library selection through `load_api()`. - Firebird 6 trace session plugin support: `ServerTraceServices.start()` accepts plugin names, and `TraceSession` reports the plugins returned by the service manager. - Configurable `Server.query_timeout` and a `TIMEOUT` sentinel for timed text output queries. @@ -25,6 +26,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed +- Decode `iUtil.get_client_version()` into major and minor version numbers. - GH-69: Avoid detaching an already released Firebird 5 attachment during garbage collection. - Keep the trace session `plugins` argument optional for existing callers. - Correct historical changelog issue references and links for Markdown rendering in Zensical. diff --git a/development/README.md b/development/README.md index d0f53f0..2e65b16 100644 --- a/development/README.md +++ b/development/README.md @@ -18,6 +18,7 @@ wrappers, types, and hooks. Read the module note before changing its source: | `fbapi.py` | [fbapi.md](fbapi.md) | `ctypes` bindings and client library loading | | `hooks.py` | [hooks.md](hooks.md) | Driver hook kinds and registration imports | | `interfaces.py` | [interfaces.md](interfaces.md) | Firebird object API wrappers | +| `provider.py` | [provider.md](provider.md) | Runtime provider contract and system-client selection | | `types.py` | [types.md](types.md) | DB API exceptions, constants, flags, and data types | The package requires Python 3.11 or newer and depends on `firebird-base` and `python-dateutil`. @@ -32,14 +33,15 @@ database entry. A working client library, server, and matching test database are needed even for many narrowly selected tests. From the repository root, `hatch test` runs the default test environment; `hatch test -a` -runs its Python 3.11–3.14 matrix. The `hatch-test` environment in `pyproject.toml` passes -`--host=localhost` by default. `tests/conftest.py` also accepts `--host`, `--port`, `--client-lib`, +runs the Python and backend matrix in `pyproject.toml`. The `local` backend passes +`--host=localhost`; `localem` uses a local embedded connection. Select a single Python 3.11 +backend during development, for example `hatch test -i backend=localem -py 3.11`. +`tests/conftest.py` also accepts `--host`, `--port`, `--client-lib`, `--driver-config`, and `--server`. Use a focused test file while developing, then run the wider suite when the prepared Firebird environment is available. Do not treat a missing server or client library as a passing test. -For embedded-mode testing, remove the `--host=localhost` extra argument from `[tool.hatch.envs.hatch-test]` -in `pyproject.toml` and provide a suitable local client library. Alternatively, use a driver +For embedded-mode testing, provide a suitable local client library. Alternatively, use a driver configuration file with `--driver-config` and select a named server with `--server`. Check `tests/conftest.py` for how these options are applied before the API is loaded. diff --git a/development/__init__.md b/development/__init__.md index 042e559..8b2db81 100644 --- a/development/__init__.md +++ b/development/__init__.md @@ -10,3 +10,4 @@ When changing a public symbol, check whether it must be exported here and docume `docs/docs/ref-main.md` or another API page. Keep implementations in their owning modules. Check imports after export changes because importing `firebird.driver` loads several implementation modules and registers API hooks. +`FirebirdProvider` is exported as a public protocol; the driver's own implementation stays private. diff --git a/development/fbapi.md b/development/fbapi.md index 4f1b039..ddb4bd3 100644 --- a/development/fbapi.md +++ b/development/fbapi.md @@ -4,8 +4,11 @@ Source: `src/firebird/driver/fbapi.py`, relative to the repository root. This is the low-level `ctypes` boundary. It defines Firebird C constants, structures, vtables, and the `FirebirdAPI` loader. `get_api()` calls `load_api()` on first use; the loaded API -is cached in the module. An explicit filename or `driver_config.fb_client_library.value` -selects the client library before first load. The `APIHook.LOADED` callbacks run after initialization. +is cached in the module. An explicit filename, provider instance, or +`driver_config.fb_client_library.value` selects the client library before first load. Filenames +are wrapped in the private driver provider; provider instances are used directly. The +`APIHook.LOADED` callbacks initialize the private provider after the master and utility +interfaces are available. Changes to C layouts, pointer types, or signatures can affect every higher-level wrapper. Compare them with the supported Firebird client API and run focused integration tests on diff --git a/development/interfaces.md b/development/interfaces.md index 0a047f1..340c5f7 100644 --- a/development/interfaces.md +++ b/development/interfaces.md @@ -12,4 +12,6 @@ disposable wrappers dispose their interfaces. Status checking translates Firebir vectors into driver errors or warnings. On `APIHook.LOADED`, the module obtains the master and utility interfaces and attaches them to the API object. Check wrapper changes against the matching `fbapi.py` declarations and run integration tests for the Firebird versions -they affect. +they affect. The same hook completes metadata for the private driver provider using the root +directory and client version reported by the loaded API. `iUtil.get_client_version()` returns +`(major, minor)`. diff --git a/development/provider.md b/development/provider.md new file mode 100644 index 0000000..bdb0bb7 --- /dev/null +++ b/development/provider.md @@ -0,0 +1,13 @@ +# `firebird.driver.provider` + +Source: `src/firebird/driver/provider.py`, relative to the repository root. + +`FirebirdProvider` is a structural protocol. External runtime packages can satisfy it without +inheriting from the driver. `_DriverProvider` is private and handles explicit client paths or +system client lookup. Its root, client version, and capabilities are initialized from the loaded +client API by the `interfaces.py` API-loaded hook. They must not be read before that step. + +The runtime root comes from `IConfigManager.get_root_directory()`, not from the client filename. +The private provider checks that root's `plugins` directory for a numbered `engineXX` shared +library to determine whether the embedded capability is present. External provider metadata +is not changed by the driver. diff --git a/docs/docs/ref-main.md b/docs/docs/ref-main.md index e0af2b7..12520b9 100644 --- a/docs/docs/ref-main.md +++ b/docs/docs/ref-main.md @@ -66,3 +66,7 @@ Helper functions: Functions `load_api()` and `get_api()`. + +### provider + +Protocol: `FirebirdProvider`. diff --git a/docs/docs/ref-provider.md b/docs/docs/ref-provider.md new file mode 100644 index 0000000..4f10724 --- /dev/null +++ b/docs/docs/ref-provider.md @@ -0,0 +1,7 @@ +# Runtime provider + +The public protocol describes the metadata a runtime provider supplies to the driver. +Applications can use the `firebird.runtime.providers` entry-point group to discover and +instantiate a provider, then pass it to `load_api()`. The driver does not choose an entry point. + +::: firebird.driver.provider.FirebirdProvider diff --git a/docs/docs/usage-guide/configuration.md b/docs/docs/usage-guide/configuration.md index 4fb676a..3140237 100644 --- a/docs/docs/usage-guide/configuration.md +++ b/docs/docs/usage-guide/configuration.md @@ -28,6 +28,24 @@ configuration string, dict or file(s). calls any from following functions: [`connect()`](../ref-core.md#firebird.driver.core.connect), [`create_database()`](../ref-core.md#firebird.driver.core.create_database), [`connect_server()`](../ref-core.md#firebird.driver.core.connect_server), [`load_api()`](../ref-fbapi.md#firebird.driver.fbapi.load_api) or [`get_api()`](../ref-fbapi.md#firebird.driver.fbapi.get_api). +You can also call `load_api(provider)` with an instance of a runtime provider, such as one +advertised by the `firebird.runtime.providers` entry-point group. Entry points expose provider +classes; select and instantiate the desired class in your application. The driver does not +automatically choose an installed provider. The selected provider is available as the read-only +`get_api().provider` property. For an explicit filename or a system client, the driver uses its +own provider and obtains the runtime root and client version after loading the API. + +For example, to select the `firebird-embedded` provider by entry-point name: + +```python +from importlib.metadata import entry_points +from firebird.driver import load_api + +provider_entry = next(ep for ep in entry_points(group='firebird.runtime.providers') + if ep.name == 'firebird') +load_api(provider_entry.load()()) +``` + !!! info [`DriverConfig`](../ref-config.md#firebird.driver.config.DriverConfig) for list of available methods and parameters. diff --git a/docs/docs/usage-guide/driver-structure.md b/docs/docs/usage-guide/driver-structure.md index 48b2ea9..9416b7e 100644 --- a/docs/docs/usage-guide/driver-structure.md +++ b/docs/docs/usage-guide/driver-structure.md @@ -6,6 +6,7 @@ Source code is currently divided into next submodules: * `interfaces` - Interface wrappers for Firebird new API * `core` - Main driver source code. * `fbapi` - Python `ctypes` interface to Firebird client library. +* `provider` - Runtime provider contract for selecting a client library. * `config` - Driver configuration. * `hooks` - Drivers hooks. diff --git a/docs/zensical.toml b/docs/zensical.toml index bd857fa..0662ed3 100644 --- a/docs/zensical.toml +++ b/docs/zensical.toml @@ -27,6 +27,7 @@ nav = [ { "Hooks" = "ref-hooks.md" }, { "Interfaces" = "ref-intf.md" }, { "Client API" = "ref-fbapi.md" }, + { "Runtime provider" = "ref-provider.md" }, ] }, { "Changelog" = "changelog.md" }, { "License" = "license.md" }, @@ -71,7 +72,7 @@ find_stubs_package = true [project.plugins.llmstxt] enabled = true -markdown_description = "For driver version 2.0.3" +markdown_description = "For driver version 2.1.0.dev0" sections = { "Usage Guide" = [ "usage-guide/driver-structure.md" , @@ -94,5 +95,6 @@ sections = { "ref-hooks.md", "ref-intf.md", "ref-fbapi.md", + "ref-provider.md", ], } diff --git a/pyproject.toml b/pyproject.toml index 5e4aee5..bbcd10b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -21,6 +21,8 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Programming Language :: Python :: 3.15", "Operating System :: POSIX :: Linux", "Operating System :: Microsoft :: Windows", "Operating System :: MacOS", @@ -56,13 +58,16 @@ dependencies = [ ] [tool.hatch.envs.hatch-test] -extra-args = ["--host=localhost"] extra-dependencies = [ "packaging>=25.0", ] [[tool.hatch.envs.hatch-test.matrix]] -python = ["3.11", "3.12", "3.13", "3.14"] +python = ["3.11", "3.12", "3.13", "3.14", "3.15"] +backend = ["local", "localem"] + +[tool.hatch.envs.hatch-test.overrides] +matrix.backend.extra-args = { value = ["--host=localhost"], if = ["local"] } [tool.hatch.envs.doc] detached = false diff --git a/src/firebird/driver/__init__.py b/src/firebird/driver/__init__.py index 0c7c6a9..036b335 100644 --- a/src/firebird/driver/__init__.py +++ b/src/firebird/driver/__init__.py @@ -56,6 +56,7 @@ transaction, ) from .fbapi import get_api, load_api +from .provider import FirebirdProvider from .types import ( BINARY, DATETIME, @@ -133,5 +134,5 @@ TIMEOUT, ) -__VERSION__ = '2.0.4.dev0' +__VERSION__ = '2.1.0.dev0' "Current driver version, SEMVER string." diff --git a/src/firebird/driver/fbapi.py b/src/firebird/driver/fbapi.py index 2880d81..2d5d94d 100644 --- a/src/firebird/driver/fbapi.py +++ b/src/firebird/driver/fbapi.py @@ -41,7 +41,6 @@ import decimal import platform import sys -from contextlib import suppress from ctypes import ( CFUNCTYPE, POINTER, @@ -64,13 +63,13 @@ cast, create_string_buffer, ) -from ctypes.util import find_library from locale import getpreferredencoding from pathlib import Path from typing import ClassVar from .config import driver_config from .hooks import APIHook, get_callbacks, register_class +from .provider import FirebirdProvider, _DriverProvider # Constants @@ -1929,10 +1928,12 @@ class FirebirdAPI: for bindings. Arguments: - filename (`~pathlib.Path`): Firebird client library to be loaded. If it's not provided, - the driver uses `ctypes.util.find_library()` to locate the library. + filename: Client library filename or runtime provider. When omitted, the driver + locates a system client library. + provider: Runtime provider supplied by keyword, as an alternative to `filename`. Attributes: + provider (`.FirebirdProvider`): Runtime provider used to load this API client_library (`ctypes.CDLL`): Loaded Firebird client library `ctypes` handler client_library_name (`~pathlib.Path`): Path to loaded Firebird client library master (iMaster): Firebird API IMaster interface @@ -2052,26 +2053,15 @@ class FirebirdAPI: Old API function. """ - def __init__(self, filename: Path | None=None): + def __init__(self, filename: FirebirdProvider | str | Path | None=None, + *, provider: FirebirdProvider | None=None): decimal.getcontext().prec = 34 - if filename is None: - if sys.platform == 'darwin': - filename = find_library('Firebird') - elif sys.platform == 'win32': - filename = find_library('fbclient.dll') - else: - filename = find_library('fbclient') - if not filename: - with suppress(Exception): - ctypes.CDLL('libfbclient.so') - filename = 'libfbclient.so' - if not filename: - raise Exception("The location of Firebird Client Library could not be determined.") - elif not filename.exists(): - file_name = find_library(filename.name) - if not file_name: - raise Exception(f"Firebird Client Library '{filename}' not found") - filename = file_name + if filename is not None and provider is not None: + raise TypeError('Specify either filename or provider') + selected = provider if provider is not None else filename + self._provider = _DriverProvider(selected) if selected is None or isinstance(selected, (str, Path)) \ + else selected + filename = self._provider.client_library self.client_library: ctypes.CDLL = None "Firebird client library" if sys.platform in ('win32', 'cygwin', 'os2', 'os2emx'): @@ -2216,6 +2206,19 @@ def __init__(self, filename: Path | None=None): self.master = None self.util = None + @property + def provider(self) -> FirebirdProvider: + """Runtime provider used by this API, available after initialization.""" + if isinstance(self._provider, _DriverProvider) and self._provider._root is None: + raise RuntimeError('Provider metadata is not initialized') + return self._provider + + def _initialize_provider(self) -> None: + """Complete metadata for the driver's own runtime provider.""" + if isinstance(self._provider, _DriverProvider): + root = self.master.get_config_manager().get_root_directory() + self._provider._initialize(root, self.util.get_client_version()) + def isc_event_block(self, event_buffer: bytes, result_buffer: bytes, *args) -> int: """Convenience wrapper for isc_event_block() API function. Injects variable number of parameters into `C_isc_event_block` call. @@ -2232,16 +2235,13 @@ def has_api() -> bool: """ return api is not None -def load_api(filename: str | Path | None=None) -> None: +def load_api(filename: str | Path | FirebirdProvider | None=None) -> None: """Initializes bindings to Firebird Client Library unless they are already initialized. Called automatically by `get_api()`. Args: - filename: Path to Firebird Client Library. - When it's not specified, driver does its best to locate appropriate client library. - - Returns: - `FirebirdAPI` instance. + filename: Client library filename or runtime provider. When omitted, the configured + filename is used, or the driver locates a system client library. Hooks: Event `HookType.HOOK_API_LOADED`: Executed after api is initialized. @@ -2251,12 +2251,18 @@ def load_api(filename: str | Path | None=None) -> None: if not has_api(): if filename is None: filename = driver_config.fb_client_library.value - if filename and not isinstance(filename, Path): - filename = Path(filename) - _api = FirebirdAPI(filename) + if isinstance(filename, str) and not filename: + filename = None + if filename is None or isinstance(filename, (str, Path)): + filename = _DriverProvider(filename) + _api = FirebirdAPI(provider=filename) setattr(sys.modules[__name__], 'api', _api) # noqa: B010 - for hook in get_callbacks(APIHook.LOADED, _api): - hook(_api) + try: + for hook in get_callbacks(APIHook.LOADED, _api): + hook(_api) + except Exception: + setattr(sys.modules[__name__], 'api', None) # noqa: B010 + raise def get_api() -> FirebirdAPI: """Returns Firebird API. Loads the API if needed. diff --git a/src/firebird/driver/interfaces.py b/src/firebird/driver/interfaces.py index 3c0358c..b3d60e3 100644 --- a/src/firebird/driver/interfaces.py +++ b/src/firebird/driver/interfaces.py @@ -2027,5 +2027,6 @@ def wrap(result, func=None, arguments=None) -> iMaster: setattr(sys.modules[__name__], '_util', _master.get_util_interface()) # noqa:B010 api.master: iMaster = _master api.util: iUtil = _util + api._initialize_provider() add_hook(APIHook.LOADED, a.FirebirdAPI, __augment_api) diff --git a/src/firebird/driver/provider.py b/src/firebird/driver/provider.py new file mode 100644 index 0000000..cfa2ba9 --- /dev/null +++ b/src/firebird/driver/provider.py @@ -0,0 +1,125 @@ +"""Runtime provider contract and the driver's system-client implementation.""" + +from __future__ import annotations + +import ctypes +import re +import sys +from contextlib import suppress +from ctypes.util import find_library +from importlib import import_module +from pathlib import Path +from typing import Protocol + + +class FirebirdProvider(Protocol): + """Description of a Firebird-compatible runtime supplied to the driver.""" + + @property + def name(self) -> str: + """Runtime implementation identifier.""" + ... + + @property + def package_version(self) -> str: + """Version of the distribution supplying this runtime.""" + ... + + @property + def firebird_version(self) -> str: + """Version of the supplied client library.""" + ... + + @property + def root(self) -> Path: + """Runtime root directory.""" + ... + + @property + def client_library(self) -> Path: + """Client library to load.""" + ... + + @property + def capabilities(self) -> frozenset[str]: + """Features supplied by this runtime.""" + ... + + +class _DriverProvider: + """Provider for an explicitly selected or system Firebird client library.""" + + def __init__(self, client_library: str | Path | None = None): + if client_library is None: + if sys.platform == 'darwin': + name = 'Firebird' + elif sys.platform == 'win32': + name = 'fbclient.dll' + else: + name = 'fbclient' + located = find_library(name) + if not located and sys.platform not in ('darwin', 'win32'): + with suppress(OSError): + ctypes.CDLL('libfbclient.so') + located = 'libfbclient.so' + if not located: + raise FileNotFoundError('The location of Firebird Client Library could not be determined.') + self._client_library = Path(located) + else: + self._client_library = Path(client_library) + if not self._client_library.is_file(): + raise FileNotFoundError(f"Firebird Client Library '{self._client_library}' not found") + self._root: Path | None = None + self._firebird_version: str | None = None + self._capabilities: frozenset[str] | None = None + + @property + def name(self) -> str: + """Runtime implementation identifier.""" + return 'firebird' + + @property + def package_version(self) -> str: + """Version of the firebird-driver distribution.""" + return import_module('firebird.driver').__VERSION__ + + @property + def firebird_version(self) -> str: + """Version of the loaded Firebird client library.""" + if self._firebird_version is None: + raise RuntimeError('Provider metadata is not initialized') + return self._firebird_version + + @property + def root(self) -> Path: + """Root directory reported by the client API.""" + if self._root is None: + raise RuntimeError('Provider metadata is not initialized') + return self._root + + @property + def client_library(self) -> Path: + """Client library to load.""" + return self._client_library + + @property + def capabilities(self) -> frozenset[str]: + """Capabilities of the loaded runtime.""" + if self._capabilities is None: + raise RuntimeError('Provider metadata is not initialized') + return self._capabilities + + def _initialize(self, root: str, version: tuple[int, int]) -> None: + """Complete metadata once the client interfaces are available.""" + runtime_root = Path(root) + if not root: + raise RuntimeError('The Firebird client did not report a root directory') + extension = 'dll' if sys.platform == 'win32' else 'so' + pattern = re.compile(rf'engine[0-9]+\.{extension}', re.IGNORECASE) + capabilities = {'client'} + plugins = runtime_root / 'plugins' + if plugins.is_dir() and any(pattern.fullmatch(path.name) for path in plugins.iterdir()): + capabilities.add('embedded') + self._root = runtime_root + self._firebird_version = f'{version[0]}.{version[1]}' + self._capabilities = frozenset(capabilities) diff --git a/unit_tests/test_client_version.py b/tests/test_client_version.py similarity index 100% rename from unit_tests/test_client_version.py rename to tests/test_client_version.py diff --git a/tests/test_provider.py b/tests/test_provider.py new file mode 100644 index 0000000..0cae53d --- /dev/null +++ b/tests/test_provider.py @@ -0,0 +1,121 @@ +"""Runtime provider tests that do not need a Firebird installation.""" + +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest + +from firebird.driver import __VERSION__, fbapi +from firebird.driver.provider import _DriverProvider + + +def test_explicit_library_is_authoritative(tmp_path, monkeypatch): + library = tmp_path / 'fbclient.so' + library.touch() + monkeypatch.setattr('firebird.driver.provider.find_library', lambda _: pytest.fail('unexpected lookup')) + + provider = _DriverProvider(library) + + assert provider.client_library == library + assert provider.name == 'firebird' + assert provider.package_version == __VERSION__ + with pytest.raises(RuntimeError, match='not initialized'): + _ = provider.root + with pytest.raises(FileNotFoundError): + _DriverProvider(tmp_path / 'missing.so') + + +def test_system_library_lookup(monkeypatch): + monkeypatch.setattr('firebird.driver.provider.find_library', lambda _: 'libfbclient.so.2') + + assert _DriverProvider().client_library == Path('libfbclient.so.2') + + +@pytest.mark.parametrize(('plugin', 'embedded'), [ + ('engine13.so', True), + ('engine.so', False), + ('engine13.so.bak', False), +]) +def test_metadata_from_loaded_client(tmp_path, plugin, embedded): + library = tmp_path / 'libfbclient.so' + library.touch() + runtime_root = tmp_path / 'runtime' + plugins = runtime_root / 'plugins' + runtime_root.mkdir() + plugins.mkdir() + (plugins / plugin).touch() + provider = _DriverProvider(library) + api = SimpleNamespace( + _provider=provider, + master=SimpleNamespace(get_config_manager=lambda: SimpleNamespace( + get_root_directory=lambda: str(runtime_root))), + util=SimpleNamespace(get_client_version=lambda: (5, 0)), + ) + + fbapi.FirebirdAPI._initialize_provider(api) + + assert provider.root == runtime_root + assert provider.firebird_version == '5.0' + assert provider.capabilities == (frozenset({'client', 'embedded'}) if embedded else frozenset({'client'})) + assert fbapi.FirebirdAPI.provider.fget(api) is provider + + +def test_firebird_api_loads_supplied_provider(tmp_path, monkeypatch): + library = tmp_path / 'libfbclient.so' + provider = SimpleNamespace(name='firebird', package_version='5.0.4.0', + firebird_version='5.0.4', root=tmp_path, + client_library=library, capabilities=frozenset({'client', 'embedded'})) + client = MagicMock() + load = MagicMock(return_value=client) + monkeypatch.setattr(fbapi.ctypes, 'CDLL', load) + monkeypatch.setattr(fbapi, 'CFUNCTYPE', lambda *_args: lambda _: SimpleNamespace(argtypes=[])) + + api = fbapi.FirebirdAPI(provider=provider) + + load.assert_called_once_with(str(library), mode=fbapi.ctypes.RTLD_GLOBAL) + assert api.provider is provider + assert api.client_library_name == library + with pytest.raises(AttributeError): + api.provider = provider + + +def test_load_api_uses_external_provider(tmp_path, monkeypatch): + provider = SimpleNamespace(client_library=tmp_path / 'fbclient.so') + seen = [] + monkeypatch.setattr(fbapi, 'api', None) + monkeypatch.setattr(fbapi, 'FirebirdAPI', lambda *, provider: seen.append(provider) or object()) + monkeypatch.setattr(fbapi, 'get_callbacks', lambda *_: []) + + fbapi.load_api(provider) + + assert seen == [provider] + + +def test_load_api_wraps_filename(tmp_path, monkeypatch): + library = tmp_path / 'fbclient.so' + library.touch() + seen = [] + monkeypatch.setattr(fbapi, 'api', None) + monkeypatch.setattr(fbapi, 'FirebirdAPI', lambda *, provider: seen.append(provider) or object()) + monkeypatch.setattr(fbapi, 'get_callbacks', lambda *_: []) + + fbapi.load_api(str(library)) + + assert isinstance(seen[0], _DriverProvider) + assert seen[0].client_library == library + + +def test_failed_initialization_does_not_cache_api(tmp_path, monkeypatch): + provider = SimpleNamespace(client_library=tmp_path / 'fbclient.so') + monkeypatch.setattr(fbapi, 'api', None) + monkeypatch.setattr(fbapi, 'FirebirdAPI', lambda *, provider: SimpleNamespace(provider=provider)) + + def fail(_): + raise RuntimeError('initialization failed') + monkeypatch.setattr(fbapi, 'get_callbacks', lambda *_: [fail]) + + with pytest.raises(RuntimeError, match='initialization failed'): + fbapi.load_api(provider) + + assert not fbapi.has_api() diff --git a/tests/test_server.py b/tests/test_server.py index 34a2aac..32cb44a 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -23,8 +23,10 @@ # See LICENSE.TXT for details. import inspect +import sys from ctypes import memmove from io import BytesIO +from shutil import copyfile import pytest from packaging.specifiers import SpecifierSet import firebird.driver as driver @@ -68,6 +70,23 @@ def service_test_env(tmp_dir, fb_vars): except OSError: pass # Ignore if removal fails +@pytest.fixture +def user_db_file(tmp_dir, fb_vars, request, server_connection): + # User services must not modify the installation's security database. + # Use a separate copy in the directory already accessible to the test server. + path = tmp_dir / f'{request.node.name}-users.fdb' + copyfile(fb_vars['source_db'], path) + if sys.platform != 'win32': + path.chmod(0o666) + try: + server_connection.user.add(user_name='SYSDBA', password=fb_vars['password'], database=path) + yield path + finally: + try: + path.unlink(missing_ok=True) + except PermissionError: + pass # Firebird may retain the database file until the service detaches. + def test_attach(server_connection): # The fixture itself tests attachment assert server_connection is not None @@ -299,8 +318,8 @@ def test_trace(server_connection, db_file, fb_vars): assert sessions[trace1_id].user == 'SYSDBA' assert sessions[trace2_id].user == 'SYSDBA' assert trace2_id in sessions - assert sessions[trace1_id].flags == ['active', ' trace'] - assert sessions[trace2_id].flags == ['active', ' trace'] + assert {'active', 'trace'} <= {flag.strip() for flag in sessions[trace1_id].flags} + assert {'active', 'trace'} <= {flag.strip() for flag in sessions[trace2_id].flags} # Pause session svcx.trace.suspend(session_id=trace2_id) assert 'suspend' in svcx.trace.sessions[trace2_id].flags @@ -313,16 +332,16 @@ def test_trace(server_connection, db_file, fb_vars): # Finalize svcx.trace.stop(session_id=trace1_id) -def test_get_users(server_connection): - users = server_connection.user.get_all() +def test_get_users(server_connection, user_db_file): + users = server_connection.user.get_all(database=user_db_file) assert isinstance(users, type(list())) assert isinstance(users[0], driver.core.UserInfo) assert users[0].user_name == 'SYSDBA' -def test_manage_user(server_connection): +def test_manage_user(server_connection, user_db_file): USER_NAME = 'DRIVER_TEST' try: - server_connection.user.delete(USER_NAME) + server_connection.user.delete(USER_NAME, database=user_db_file) except DatabaseError as e: if e.sqlstate == '28000': pass @@ -330,24 +349,26 @@ def test_manage_user(server_connection): raise # Add user server_connection.user.add(user_name=USER_NAME, password='DRIVER_TEST', - first_name='Firebird', middle_name='Driver', last_name='Test') - assert server_connection.user.exists(USER_NAME) - users = [u for u in server_connection.user.get_all() if u.user_name == USER_NAME] + first_name='Firebird', middle_name='Driver', last_name='Test', + database=user_db_file) + assert server_connection.user.exists(USER_NAME, database=user_db_file) + users = [u for u in server_connection.user.get_all(database=user_db_file) if u.user_name == USER_NAME] assert users assert len(users) == 1 assert users[0].first_name == 'Firebird' assert users[0].middle_name == 'Driver' assert users[0].last_name == 'Test' # Modify user - server_connection.user.update(USER_NAME, first_name='XFirebird', middle_name='XDriver', last_name='XTest') - user = server_connection.user.get(USER_NAME) + server_connection.user.update(USER_NAME, first_name='XFirebird', middle_name='XDriver', + last_name='XTest', database=user_db_file) + user = server_connection.user.get(USER_NAME, database=user_db_file) assert user.user_name == USER_NAME assert user.first_name == 'XFirebird' assert user.middle_name == 'XDriver' assert user.last_name == 'XTest' # Delete user - server_connection.user.delete(USER_NAME) - assert not server_connection.user.exists(USER_NAME) + server_connection.user.delete(USER_NAME, database=user_db_file) + assert not server_connection.user.exists(USER_NAME, database=user_db_file) def test_get_statistics(server_connection, db_file): def fetchline(line): From 40da87bf98bf5749c87d4ce47530902eaa8ee55a Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Thu, 15 Oct 2026 14:42:48 +0200 Subject: [PATCH 31/48] Support embedded provider test backends and log metadata --- AGENTS.md | 3 +++ CHANGELOG.md | 4 ++++ development/README.md | 11 ++++++++--- development/provider.md | 3 +++ pyproject.toml | 9 ++++++++- src/firebird/driver/provider.py | 10 ++++++++++ tests/conftest.py | 27 ++++++++++++++++++++++++--- tests/test_provider.py | 20 ++++++++++++++++++++ tests/test_server.py | 12 ++++++------ 9 files changed, 86 insertions(+), 13 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a7574c8..8a44370 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,3 +17,6 @@ This file applies to the repository root. All paths below are relative to that r - Check `git status` before editing and preserve unrelated work. Verify changes with the focused tests and build commands described in the development README; report any Firebird-dependent checks that could not run. +- Check pytest's `Firebird:` session header against the intended backend when changing tests or + fixtures: it reports the configuration, server/version, host, client library, and selected test + database. The displayed database path is the source file; fixtures test a temporary copy. diff --git a/CHANGELOG.md b/CHANGELOG.md index 35663e6..aea537f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Added - A runtime provider protocol and provider-based client library selection through `load_api()`. +- An optional `FirebirdProvider.firebird_log` path for runtimes with a directly accessible log. - Firebird 6 trace session plugin support: `ServerTraceServices.start()` accepts plugin names, and `TraceSession` reports the plugins returned by the service manager. - Configurable `Server.query_timeout` and a `TIMEOUT` sentinel for timed text output queries. @@ -23,6 +24,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/). the API reference and docset workflow. - Split the usage guide into topic pages and corrected examples, links, and API descriptions. - Updated repository funding information and removed the unused `gdocs` build environment. +- Added Firebird 3, 4, and 5 embedded test backends with provider selection and runtime details + in the pytest session header. ### Fixed @@ -30,6 +33,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - GH-69: Avoid detaching an already released Firebird 5 attachment during garbage collection. - Keep the trace session `plugins` argument optional for existing callers. - Correct historical changelog issue references and links for Markdown rendering in Zensical. +- Allow server log tests to pass when the log exists but has no entries. ## [2.0.3] - 2026-04-20 diff --git a/development/README.md b/development/README.md index 2e65b16..1399720 100644 --- a/development/README.md +++ b/development/README.md @@ -41,9 +41,14 @@ backend during development, for example `hatch test -i backend=localem -py 3.11` wider suite when the prepared Firebird environment is available. Do not treat a missing server or client library as a passing test. -For embedded-mode testing, provide a suitable local client library. Alternatively, use a driver -configuration file with `--driver-config` and select a named server with `--server`. Check -`tests/conftest.py` for how these options are applied before the API is loaded. +At startup, the tests inspect entry points in `firebird.runtime.providers`. With one provider, +they set `FIREBIRD` to its runtime root and load its client library before any connection; with +more than one, setup stops with an error. Without a registered provider, the configured or system +client library is used. The pytest `Firebird:` header reports the loaded provider and the selected +source database, which the fixtures copy for the run. The `fb3em` backend installs +`firebird-embedded~=3.0`; check that its header reports Firebird 3 and `fbtest30.fdb`. +Alternatively, use a driver configuration file with `--driver-config` and select a named server +with `--server`. ## Documentation and packaging diff --git a/development/provider.md b/development/provider.md index bdb0bb7..6d312d8 100644 --- a/development/provider.md +++ b/development/provider.md @@ -11,3 +11,6 @@ The runtime root comes from `IConfigManager.get_root_directory()`, not from the The private provider checks that root's `plugins` directory for a numbered `engineXX` shared library to determine whether the embedded capability is present. External provider metadata is not changed by the driver. + +`firebird_log` is an optional local path in the public protocol. The private driver provider +returns `None` because a client library does not identify the log of the server it connects to. diff --git a/pyproject.toml b/pyproject.toml index bbcd10b..d5f6833 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -64,10 +64,17 @@ extra-dependencies = [ [[tool.hatch.envs.hatch-test.matrix]] python = ["3.11", "3.12", "3.13", "3.14", "3.15"] -backend = ["local", "localem"] +#backend = ["local", "localem"] +backend = ["local", "localem", "fb3em", "fb4em", "fb5em"] + [tool.hatch.envs.hatch-test.overrides] matrix.backend.extra-args = { value = ["--host=localhost"], if = ["local"] } +matrix.backend.extra-dependencies = [ + { value = "firebird-embedded~=3.0", if = ["fb3em"] }, + { value = "firebird-embedded~=4.0", if = ["fb4em"] }, + { value = "firebird-embedded~=5.0", if = ["fb5em"] }, +] [tool.hatch.envs.doc] detached = false diff --git a/src/firebird/driver/provider.py b/src/firebird/driver/provider.py index cfa2ba9..940febd 100644 --- a/src/firebird/driver/provider.py +++ b/src/firebird/driver/provider.py @@ -40,6 +40,11 @@ def client_library(self) -> Path: """Client library to load.""" ... + @property + def firebird_log(self) -> Path | None: + """Path to a directly accessible Firebird log, if available.""" + ... + @property def capabilities(self) -> frozenset[str]: """Features supplied by this runtime.""" @@ -102,6 +107,11 @@ def client_library(self) -> Path: """Client library to load.""" return self._client_library + @property + def firebird_log(self) -> Path | None: + """The system client's Firebird log location is not known.""" + return None + @property def capabilities(self) -> frozenset[str]: """Capabilities of the loaded runtime.""" diff --git a/tests/conftest.py b/tests/conftest.py index 14d72e9..82b9873 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -36,6 +36,8 @@ from __future__ import annotations from pathlib import Path +from importlib.metadata import entry_points +import os import platform from shutil import copyfile from configparser import ConfigParser @@ -44,7 +46,7 @@ from packaging.specifiers import SpecifierSet from packaging.version import parse from firebird.base.config import EnvExtendedInterpolation -from firebird.driver import driver_config, get_api, connect_server, connect, DbInfoCode +from firebird.driver import driver_config, get_api, load_api, connect_server, connect, DbInfoCode from firebird.base.config import ConfigProto _vars_: dict = {'client-lib': None, @@ -60,6 +62,14 @@ # Configuration +def _registered_provider(): + """Load the sole installed runtime provider, if there is one.""" + providers = list(entry_points(group='firebird.runtime.providers')) + if len(providers) > 1: + names = ', '.join(f'{item.name} ({item.value})' for item in providers) + pytest.exit(f'Multiple Firebird runtime providers are registered: {names}') + return providers[0].load()() if providers else None + def pytest_addoption(parser, pluginmanager): """Adds specific pytest command-line options. @@ -131,8 +141,13 @@ def pytest_configure(config): driver_config.server_defaults.port.value = config.getoption('port') driver_config.server_defaults.user.value = 'SYSDBA' driver_config.server_defaults.password.value = 'masterkey' - # THIS should load the driver API, do not connect db or server earlier! - _vars_['client-lib'] = get_api().client_library_name + # Select a bundled runtime before the first client API load or connection. + if provider := _registered_provider(): + os.environ['FIREBIRD'] = str(provider.root) + load_api(provider) + api = get_api() + _vars_['client-lib'] = api.client_library_name + _vars_['provider'] = api.provider # Information from server with connect_server('') as srv: version = parse(srv.info.version.replace('-dev', '')) @@ -165,6 +180,7 @@ def pytest_report_header(config): .. seealso:: `pytest documentation <_pytest.hookspec.pytest_report_header>` for details. """ + provider = _vars_['provider'] return ["Firebird:", f" configuration: {_vars_['firebird-config']}", f" server: {_vars_['server']} [v{_vars_['version']}, {_vars_['arch']}]", @@ -172,6 +188,11 @@ def pytest_report_header(config): f" home: {_vars_['home-dir']}", f" bin: {_vars_['bin-dir']}", f" client library: {_vars_['client-lib']}", + f" provider: {provider.name} ({type(provider).__module__}.{type(provider).__qualname__})", + f" provider package: {provider.package_version}", + f" provider Firebird: {provider.firebird_version}", + f" provider root: {provider.root}", + f" provider capabilities: {', '.join(sorted(provider.capabilities))}", f" test database: {_vars_['source_db']}", ] diff --git a/tests/test_provider.py b/tests/test_provider.py index 0cae53d..6b985bd 100644 --- a/tests/test_provider.py +++ b/tests/test_provider.py @@ -5,11 +5,31 @@ from unittest.mock import MagicMock import pytest +import conftest from firebird.driver import __VERSION__, fbapi from firebird.driver.provider import _DriverProvider +def test_registered_provider_selection(monkeypatch): + provider = object() + entry = SimpleNamespace(name='embedded', value='package:Provider', load=lambda: lambda: provider) + monkeypatch.setattr(conftest, 'entry_points', lambda *, group: [entry] if group == 'firebird.runtime.providers' else []) + + assert conftest._registered_provider() is provider + + monkeypatch.setattr(conftest, 'entry_points', lambda *, group: []) + assert conftest._registered_provider() is None + + +def test_multiple_registered_providers_abort_configuration(monkeypatch): + entries = [SimpleNamespace(name=name, value=f'{name}:Provider') for name in ('first', 'second')] + monkeypatch.setattr(conftest, 'entry_points', lambda *, group: entries) + + with pytest.raises(pytest.exit.Exception, match='Multiple Firebird runtime providers.*first.*second'): + conftest._registered_provider() + + def test_explicit_library_is_authoritative(tmp_path, monkeypatch): library = tmp_path / 'fbclient.so' library.touch() diff --git a/tests/test_server.py b/tests/test_server.py index 32cb44a..01e5360 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -153,17 +153,17 @@ def fetchline(line): server_connection.info.get_log() # fetch materialized log = server_connection.readlines() - assert log - assert isinstance(log, type(list())) + # A fresh embedded installation can have an empty log. Check that all + # output methods agree without generating a log entry just for this test. + assert isinstance(log, list) # iterate over result server_connection.info.get_log() - for line in server_connection: - assert line is not None - assert isinstance(line, str) + iterated = list(server_connection) + assert iterated == log + assert all(isinstance(line, str) for line in iterated) # callback output = [] server_connection.info.get_log(callback=fetchline) - assert len(output) > 0 assert output == log def test_output_by_line(server_connection): From 67f7a99659d6f3eacc8910b512f3da6af96156d8 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Thu, 15 Oct 2026 17:03:18 +0200 Subject: [PATCH 32/48] Fix local backup test across Firebird versions --- tests/test_server.py | 38 ++++++++++++++++++++++++-------------- 1 file changed, 24 insertions(+), 14 deletions(-) diff --git a/tests/test_server.py b/tests/test_server.py index 01e5360..057c82e 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -497,23 +497,33 @@ def fetchline(line): c.execute('select * from country') assert len(c.fetchall()) > 0 -def test_local_backup(server_connection, db_file, service_test_env): +def test_local_backup(server_connection, db_file, dsn, service_test_env): fbk = service_test_env['fbk'] - server_connection.database.backup(database=db_file, backup=fbk) - server_connection.wait() - with open(fbk, mode='rb') as f: - f.seek(68) # Wee must skip after backup creation time (68) that will differ - bkp = f.read() + rfdb = service_test_env['rfdb'] + rfdb_dsn = service_test_env['rfdb_dsn'] + with connect(dsn) as source: + with source.cursor() as cursor: + cursor.execute('select country, currency from country order by country') + expected_countries = cursor.fetchall() + cursor.execute('select count(*) from sales') + expected_sales_count = cursor.fetchone()[0] + assert expected_countries + assert expected_sales_count > 0 + backup_stream = BytesIO() server_connection.database.local_backup(database=db_file, backup_stream=backup_stream) - backup_stream.seek(68) - lbkp = backup_stream.read() - stop = min(len(bkp), len(lbkp)) - i = 0 - while i < stop: - assert bkp[i] == lbkp[i] - i += 1 - del bkp + assert backup_stream.tell() > 0 + # Restore the streamed backup through the regular file-based service path. + # This verifies its contents without relying on version-specific backup bytes. + fbk.write_bytes(backup_stream.getvalue()) + server_connection.database.restore(backup=fbk, database=rfdb, flags=SrvRestoreFlag.REPLACE) + server_connection.wait() + with connect(rfdb_dsn) as restored: + with restored.cursor() as cursor: + cursor.execute('select country, currency from country order by country') + assert cursor.fetchall() == expected_countries + cursor.execute('select count(*) from sales') + assert cursor.fetchone()[0] == expected_sales_count def test_local_restore(server_connection, db_file, service_test_env): rfdb = service_test_env['rfdb'] From ce4c20bb044cad81842bc178cb03ea050769665f Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Thu, 15 Oct 2026 17:28:42 +0200 Subject: [PATCH 33/48] Fix Firebird 3 tests and document feature version guards --- AGENTS.md | 3 +++ CHANGELOG.md | 5 +++++ development/README.md | 13 +++++++++++++ tests/conftest.py | 6 ++++-- tests/test_connection.py | 12 +++++++----- tests/test_hooks.py | 37 ++++++++++++++++++++---------------- tests/test_info_providers.py | 10 ++++++---- tests/test_param_buffers.py | 16 +++++++++------- tests/test_server.py | 13 +++++++------ 9 files changed, 75 insertions(+), 40 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 8a44370..adcf9a4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,3 +20,6 @@ This file applies to the repository root. All paths below are relative to that r - Check pytest's `Firebird:` session header against the intended backend when changing tests or fixtures: it reports the configuration, server/version, host, client library, and selected test database. The displayed database path is the source file; fixtures test a temporary copy. +- Guard version-specific features in tests and driver code. Record introduction versions and any + separate minor-release thresholds for supported Firebird branches in `development/` when adding + or changing a guard; do not assume one lower-bound check covers every branch. diff --git a/CHANGELOG.md b/CHANGELOG.md index aea537f..ec1136d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Updated repository funding information and removed the unused `gdocs` build environment. - Added Firebird 3, 4, and 5 embedded test backends with provider selection and runtime details in the pytest session header. +- Documented version guards for Firebird features introduced in separate minor releases of + supported branches. ### Fixed @@ -34,6 +36,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Keep the trace session `plugins` argument optional for existing callers. - Correct historical changelog issue references and links for Markdown rendering in Zensical. - Allow server log tests to pass when the log exists but has no entries. +- Isolate connection hooks between tests and close the connection supplied by the attach hook test. +- Make Firebird 3 integration tests respect feature availability, roll back failed fixture cleanup, + and avoid timing assumptions for short service actions. ## [2.0.3] - 2026-04-20 diff --git a/development/README.md b/development/README.md index 1399720..2831229 100644 --- a/development/README.md +++ b/development/README.md @@ -50,6 +50,19 @@ source database, which the fixtures copy for the run. The `fb3em` backend instal Alternatively, use a driver configuration file with `--driver-config` and select a named server with `--server`. +## Firebird feature versions + +Guard test cases and driver code that use version-specific Firebird features against the tested +engine version. Features remain available in later releases, but a feature introduced in minor +releases of multiple supported branches needs a separate threshold for each branch. For example, +if a feature first appears in 3.0.6 and 4.0.2, a check for `>=3.0.6` would incorrectly allow +4.0.0 and 4.0.1. Express that case as `>=3.0.6,<4.0` or `>=4.0.2`, and document the actual +thresholds beside the guard and here or in the matching module note. Do not infer availability +from the major version alone when a feature was introduced in a minor release. + +Current test examples: snapshot-number and READ CONSISTENCY transaction parameters require +Firebird 4.0 or newer; `SET DEBUG OPTION DSQL_KEEP_BLR` requires Firebird 4.0.1 or newer. + ## Documentation and packaging From the repository root, `hatch run doc:build` builds `docs/zensical.toml` and the Markdown diff --git a/tests/conftest.py b/tests/conftest.py index 82b9873..ed1f081 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -247,15 +247,17 @@ def db_connection(driver_cfg): conn.close() @pytest.fixture(autouse=True) -def db_cleanup(db_connection): +def db_cleanup(db_connection, fb_vars): # Clean common test tables before each test using this fixture try: with db_connection.cursor() as cur: cur.execute("delete from t") cur.execute("delete from t2") - cur.execute("delete from FB4") + if fb_vars['version'] in SpecifierSet('>=4.0'): + cur.execute("delete from FB4") db_connection.commit() except Exception as e: + db_connection.rollback() # Ignore errors if tables don't exist, log others if "Table unknown" not in str(e): print(f"Warning: Error during pre-test cleanup: {e}") diff --git a/tests/test_connection.py b/tests/test_connection.py index b5a035a..fc1f0ff 100644 --- a/tests/test_connection.py +++ b/tests/test_connection.py @@ -372,11 +372,13 @@ def test_db_info(db_connection, fb_vars, db_file): assert isinstance(con.info.get_info(DbInfoCode.ODS_MINOR_VERSION), int) assert con.info.get_info(DbInfoCode.CRYPT_KEY) == '' - assert con.info.get_info(DbInfoCode.CRYPT_PLUGIN) == '' - # DB_GUID can vary, just check format if needed - guid = con.info.get_info(DbInfoCode.DB_GUID) - assert isinstance(guid, str) - assert len(guid) == 38 # Example check for {GUID} format + # These database info items were introduced in Firebird 4.0. + if fb_vars['version'].major >= 4: + assert con.info.get_info(DbInfoCode.CRYPT_PLUGIN) == '' + # DB_GUID can vary, just check format if needed + guid = con.info.get_info(DbInfoCode.DB_GUID) + assert isinstance(guid, str) + assert len(guid) == 38 # Example check for {GUID} format def test_connect_with_driver_config_server_defaults_local(driver_cfg, db_file, fb_vars): """ diff --git a/tests/test_hooks.py b/tests/test_hooks.py index b4ba9ad..9eea7a9 100644 --- a/tests/test_hooks.py +++ b/tests/test_hooks.py @@ -36,6 +36,12 @@ def _reset_hook_state(): hook_state.clear() hook_manager.remove_all_hooks() +@pytest.fixture(autouse=True) +def isolated_hooks(): + _reset_hook_state() + yield + _reset_hook_state() + def _hook_service_attached(svc): hook_state.append("Service attached") @@ -72,29 +78,30 @@ def hook_svc(fb_vars): yield svc def test_hook_db_attached(dsn): - _reset_hook_state() add_hook(ConnectionHook.ATTACHED, Connection, _hook_db_attached) with connect(dsn) as con: assert len(hook_state) == 1 assert hook_state[0] == "Database attached" def test_hook_db_attach_request(dsn): - _reset_hook_state() main_con = connect(dsn) - add_hook(ConnectionHook.ATTACH_REQUEST, Connection, _hook_db_attach_request_a) - with connect(dsn) as con: - assert len(hook_state) == 1 - assert hook_state[0] == "Database attach request NORMAL CONNECT" - - add_hook(ConnectionHook.ATTACH_REQUEST, Connection, partial(_hook_db_attach_request_b, - hook_con_instance=main_con)) - con = connect(dsn) - assert len(hook_state) == 3 - assert hook_state[2] == "Database attach request PROVIDE CONNECTION" - assert con is main_con + try: + add_hook(ConnectionHook.ATTACH_REQUEST, Connection, _hook_db_attach_request_a) + with connect(dsn) as con: + assert len(hook_state) == 1 + assert hook_state[0] == "Database attach request NORMAL CONNECT" + + add_hook(ConnectionHook.ATTACH_REQUEST, Connection, partial(_hook_db_attach_request_b, + hook_con_instance=main_con)) + con = connect(dsn) + assert len(hook_state) == 3 + assert hook_state[2] == "Database attach request PROVIDE CONNECTION" + assert con is main_con + finally: + hook_manager.remove_all_hooks() + main_con.close() def test_hook_db_closed(dsn): - _reset_hook_state() with connect(dsn) as con: con._test_id_ = 'OUR CONENCTION' add_hook(ConnectionHook.CLOSED, con, _hook_db_closed) @@ -102,7 +109,6 @@ def test_hook_db_closed(dsn): assert hook_state[0] == "Database closed: OUR CONENCTION" def test_hook_db_detach_request(dsn): - _reset_hook_state() # reject detach con = connect(dsn) con._test_id_ = 'OUR CONENCTION' @@ -121,7 +127,6 @@ def test_hook_db_detach_request(dsn): assert con.is_closed() def test_hook_service_attached(fb_vars): - _reset_hook_state() add_hook(ServerHook.ATTACHED, Server, _hook_service_attached) with connect_server(fb_vars['host'], user=fb_vars['user'], password=fb_vars['password']) as svc: assert len(hook_state) == 1 diff --git a/tests/test_info_providers.py b/tests/test_info_providers.py index 2ca2f9a..40afee3 100644 --- a/tests/test_info_providers.py +++ b/tests/test_info_providers.py @@ -40,12 +40,14 @@ # --- Fixtures --- @pytest.fixture() -def prepared_statement(db_connection): +def prepared_statement(db_connection, fb_vars): """Provides a prepared statement for statement info tests.""" # This is needed for StmtInfoCode.EXEC_PATH_BLR_BYTES and EXEC_PATH_BLR_TEXT to work - with db_connection.cursor() as cur: - cur.execute('set debug option dsql_keep_blr = true') - db_connection.commit() + # SET DEBUG OPTION was introduced in Firebird 4.0.1. + if fb_vars['version'] in SpecifierSet('>=4.0.1'): + with db_connection.cursor() as cur: + cur.execute('set debug option dsql_keep_blr = true') + db_connection.commit() # Need a transaction active for prepare with db_connection.transaction_manager() as tm: with tm.cursor() as cur: diff --git a/tests/test_param_buffers.py b/tests/test_param_buffers.py index 206e47c..f45a4e8 100644 --- a/tests/test_param_buffers.py +++ b/tests/test_param_buffers.py @@ -41,7 +41,7 @@ from firebird.driver.types import (TraAccessMode, Isolation, TableShareMode, TableAccessMode, DBKeyScope, ReplicaMode, DecfloatRound, DecfloatTraps) -def test_tpb_parsing(): +def test_tpb_parsing(fb_vars): """Tests TPB buffer creation and parsing.""" # Test case 1: Default values tpb1 = TPB() @@ -64,7 +64,7 @@ def test_tpb_parsing(): no_auto_undo=True, auto_commit=True, ignore_limbo=True, - at_snapshot_number=12345, + at_snapshot_number=12345 if fb_vars['version'].major >= 4 else None, encoding='iso8859_1') tpb1.reserve_table('TABLE1', TableShareMode.PROTECTED, TableAccessMode.LOCK_READ) tpb1.reserve_table('TABLE2', TableShareMode.SHARED, TableAccessMode.LOCK_WRITE) @@ -90,11 +90,13 @@ def test_tpb_parsing(): assert tpb1.isolation == tpb2.isolation assert tpb1.lock_timeout == tpb2.lock_timeout - tpb1 = TPB(isolation=Isolation.READ_COMMITTED_READ_CONSISTENCY) - buffer1 = tpb1.get_buffer() - tpb2 = TPB() - tpb2.parse_buffer(buffer1) - assert tpb1.isolation == tpb2.isolation + # Snapshot sharing and READ CONSISTENCY were introduced in Firebird 4.0. + if fb_vars['version'].major >= 4: + tpb1 = TPB(isolation=Isolation.READ_COMMITTED_READ_CONSISTENCY) + buffer1 = tpb1.get_buffer() + tpb2 = TPB() + tpb2.parse_buffer(buffer1) + assert tpb1.isolation == tpb2.isolation def test_dpb_parsing(): """Tests DPB buffer creation and parsing.""" diff --git a/tests/test_server.py b/tests/test_server.py index 057c82e..1043c74 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -131,18 +131,19 @@ def test_query(server_connection, fb_vars, dsn, db_file): with pytest.raises(Error, match="feature is not supported"): # More specific error? svc.info.get_info(255) # Use an invalid code -def test_running(server_connection): - assert not server_connection.is_running() - server_connection.info.get_log() # Start an async service +def test_running(server_connection, monkeypatch): + # A real service can finish before its state is queried, especially with an empty log. + states = iter((1, 0)) + def running(info_code): + assert info_code is SrvInfoCode.RUNNING + return next(states) + monkeypatch.setattr(server_connection.info, 'get_info', running) assert server_connection.is_running() - # fetch materialized - server_connection.readlines() # Read all output assert not server_connection.is_running() def test_wait(server_connection): assert not server_connection.is_running() server_connection.info.get_log() - assert server_connection.is_running() server_connection.wait() # Wait for service to finish assert not server_connection.is_running() From a585a3d71bfa9b566c81d2e42ef36c4352c0c934 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Tue, 20 Oct 2026 18:56:21 +0200 Subject: [PATCH 34/48] Remove relict --- src/test.py | 24 ------------------------ 1 file changed, 24 deletions(-) delete mode 100644 src/test.py diff --git a/src/test.py b/src/test.py deleted file mode 100644 index 467953a..0000000 --- a/src/test.py +++ /dev/null @@ -1,24 +0,0 @@ -import sys -import os - -from firebird.driver.fbapi import load_api -sys.path.append(os.getcwd()) -script_dir = os.path.dirname(os.path.abspath(__file__)) -sys.path.append(script_dir) -from firebird.driver.core import connect_server - -load_api("/home/artmkn/wspace/reps/rdb5trace/gen/Debug/firebird/lib/libfbclient.so") - -with connect_server('', user='SYSDBA', password='masterkey') as srv: - - trace_session_id = srv.trace.start(config="#MESSAGETRACE\ndatabase\n{\nenabled = true\n}", name="messagetrace") - print(trace_session_id) - - a = input() - # K = 1 - # V = TraceSession(id=1, user='SYSDBA', timestamp=..., name=, flags=['active', ' trace']) - # for k,v in srv.trace.sessions.items(): - # if v.flags[0] == 'active': - # print(f"Trace {v.name}: Plugins: {v.plugins}") - - From 72d0dc31f7d32ae4a1f79022fc4efbca18657bb3 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Fri, 23 Oct 2026 12:55:17 +0200 Subject: [PATCH 35/48] Fix keyhoder to keyholder parameter name; fix typos in documentation --- src/firebird/driver/core.py | 49 +++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 26 deletions(-) diff --git a/src/firebird/driver/core.py b/src/firebird/driver/core.py index f51c32d..09e91ee 100644 --- a/src/firebird/driver/core.py +++ b/src/firebird/driver/core.py @@ -2144,7 +2144,7 @@ def tpb(isolation: Isolation, lock_timeout: int=INFINITE_TIMEOUT, Arguments: isolation: Isolation level. lock_timeout: Lock timeout (-1 = Infinity) - access: Access mode. + access_mode: Access mode. """ return TPB(isolation=isolation, lock_timeout=lock_timeout, access_mode=access_mode).get_buffer() @@ -3345,7 +3345,7 @@ def __init__(self, connection: Connection, transaction: TransactionManager): self.stream_blobs: list[str] = [] "Names of columns that should be returned as `BlobReader`." self.stream_blob_threshold = driver_config.stream_blob_threshold.value - "BLOBs greater than threshold are returned as `BlobReader` instead in materialized form.\nDefaults to the value from `driver_config`." + "BLOBs greater than threshold are returned as `BlobReader` instead of materialized values.\nSet to -1 to disable automatic streaming. Defaults to the value from `driver_config`." def __enter__(self) -> Self: return self def __exit__(self, exc_type, exc_value, traceback) -> None: @@ -4550,7 +4550,7 @@ def backup(self, *, database: FILESPEC, backup: FILESPEC | Sequence[FILESPEC], flags: SrvBackupFlag=SrvBackupFlag.NONE, role: str | None=None, callback: CB_OUTPUT_LINE | None=None, stats: str | None=None, verbose: bool=False, verbint: int | None=None, skip_data: str | None=None, - include_data: str | None=None, keyhoder: str | None=None, keyname: str | None=None, + include_data: str | None=None, keyholder: str | None=None, keyname: str | None=None, crypt: str | None=None, parallel_workers: int | None=None) -> None: """Request logical (GBAK) database backup. **(ASYNC service)** @@ -4566,7 +4566,7 @@ def backup(self, *, database: FILESPEC, backup: FILESPEC | Sequence[FILESPEC], verbint: Verbose information with explicit interval (number of records) skip_data: String with table names whose data should be excluded from backup. include_data: String with table names whose data should be included into backup [Firebird 4]. - keyholder: Keyholder name [Firebird 4] + keyholder: Keyholder name [Firebird 4]. keyname: Key name [Firebird 4] crypt: Encryption specification [Firebird 4] parallel_workers: Number of parallel workers [Firebird 5] @@ -4587,8 +4587,8 @@ def backup(self, *, database: FILESPEC, backup: FILESPEC | Sequence[FILESPEC], spb.insert_string(SrvBackupOption.SKIP_DATA, skip_data) if include_data is not None: spb.insert_string(SrvBackupOption.INCLUDE_DATA, include_data) - if keyhoder is not None: - spb.insert_string(SrvBackupOption.KEYHOLDER, keyhoder) + if keyholder is not None: + spb.insert_string(SrvBackupOption.KEYHOLDER, keyholder) if keyname is not None: spb.insert_string(SrvBackupOption.KEYNAME, keyname) if crypt is not None: @@ -4614,7 +4614,7 @@ def restore(self, *, backup: FILESPEC | Sequence[FILESPEC], verbose: bool=False, verbint: int | None=None, skip_data: str | None=None, page_size: int | None=None, buffers: int | None=None, access_mode: DbAccessMode=DbAccessMode.READ_WRITE, include_data: str | None=None, - keyhoder: str | None=None, keyname: str | None=None, crypt: str | None=None, + keyholder: str | None=None, keyname: str | None=None, crypt: str | None=None, replica_mode: ReplicaMode | None=None, parallel_workers: int | None=None) -> None: """Request database restore from logical (GBAK) backup. **(ASYNC service)** @@ -4633,7 +4633,7 @@ def restore(self, *, backup: FILESPEC | Sequence[FILESPEC], buffers: Cache size for restored database. access_mode: Restored database access mode (R/W or R/O). include_data: String with table names whose data should be included into backup [Firebird 4]. - keyholder: Keyholder name [Firebird 4] + keyholder: Keyholder name [Firebird 4]. keyname: Key name [Firebird 4] crypt: Encryption specification [Firebird 4] replica_mode: Replica mode for restored database [Firebird 4] @@ -4663,8 +4663,8 @@ def restore(self, *, backup: FILESPEC | Sequence[FILESPEC], spb.insert_string(SrvRestoreOption.SKIP_DATA, skip_data, encoding=self._srv().encoding) if include_data is not None: spb.insert_string(SrvRestoreOption.INCLUDE_DATA, include_data, encoding=self._srv().encoding) - if keyhoder is not None: - spb.insert_string(SrvRestoreOption.KEYHOLDER, keyhoder) + if keyholder is not None: + spb.insert_string(SrvRestoreOption.KEYHOLDER, keyholder) if keyname is not None: spb.insert_string(SrvRestoreOption.KEYNAME, keyname) if crypt is not None: @@ -4686,7 +4686,7 @@ def restore(self, *, backup: FILESPEC | Sequence[FILESPEC], callback(line) def local_backup(self, *, database: FILESPEC, backup_stream: BinaryIO, flags: SrvBackupFlag=SrvBackupFlag.NONE, role: str | None=None, - skip_data: str | None=None, include_data: str | None=None, keyhoder: str | None=None, + skip_data: str | None=None, include_data: str | None=None, keyholder: str | None=None, keyname: str | None=None, crypt: str | None=None) -> None: """Request logical (GBAK) database backup into local byte stream. **(SYNC service)** @@ -4697,7 +4697,7 @@ def local_backup(self, *, database: FILESPEC, backup_stream: BinaryIO, role: SQL ROLE name passed to gbak. skip_data: String with table names whose data should be excluded from backup. include_data: String with table names whose data should be included into backup [Firebird 4]. - keyholder: Keyholder name [Firebird 4] + keyholder: Keyholder name [Firebird 4]. keyname: Key name [Firebird 4] crypt: Encryption specification [Firebird 4] """ @@ -4715,8 +4715,8 @@ def local_backup(self, *, database: FILESPEC, backup_stream: BinaryIO, if include_data is not None: spb.insert_string(SrvBackupOption.INCLUDE_DATA, include_data, encoding=self._srv().encoding) - if keyhoder is not None: - spb.insert_string(SrvBackupOption.KEYHOLDER, keyhoder) + if keyholder is not None: + spb.insert_string(SrvBackupOption.KEYHOLDER, keyholder) if keyname is not None: spb.insert_string(SrvBackupOption.KEYNAME, keyname) if crypt is not None: @@ -4730,7 +4730,7 @@ def local_restore(self, *, backup_stream: BinaryIO, flags: SrvRestoreFlag=SrvRestoreFlag.CREATE, role: str | None=None, skip_data: str | None=None, page_size: int | None=None, buffers: int | None=None, access_mode: DbAccessMode=DbAccessMode.READ_WRITE, - include_data: str | None=None, keyhoder: str | None=None, keyname: str | None=None, + include_data: str | None=None, keyholder: str | None=None, keyname: str | None=None, crypt: str | None=None, replica_mode: ReplicaMode | None=None) -> None: """Request database restore from logical (GBAK) backup stored in local byte stream. **(SYNC service)** @@ -4746,7 +4746,7 @@ def local_restore(self, *, backup_stream: BinaryIO, buffers: Cache size for restored database. access_mode: Restored database access mode (R/W or R/O). include_data: String with table names whose data should be included into backup [Firebird 4]. - keyholder: Keyholder name [Firebird 4] + keyholder: Keyholder name [Firebird 4]. keyname: Key name [Firebird 4] crypt: Encryption specification [Firebird 4] replica_mode: Replica mode for restored database [Firebird 4] @@ -4772,8 +4772,8 @@ def local_restore(self, *, backup_stream: BinaryIO, if include_data is not None: spb.insert_string(SrvRestoreOption.INCLUDE_DATA, include_data, encoding=self._srv().encoding) - if keyhoder is not None: - spb.insert_string(SrvRestoreOption.KEYHOLDER, keyhoder) + if keyholder is not None: + spb.insert_string(SrvRestoreOption.KEYHOLDER, keyholder) if keyname is not None: spb.insert_string(SrvRestoreOption.KEYNAME, keyname) if crypt is not None: @@ -5093,13 +5093,12 @@ def validate(self, *, database: FILESPEC, include_table: str | None=None, Arguments: database: Database specification or alias. - flags: Repair flags. include_table: Regex pattern for table names to include in validation run. exclude_table: Regex pattern for table names to exclude in validation run. include_index: Regex pattern for index names to include in validation run. exclude_index: Regex pattern for index names to exclude in validation run. lock_timeout: Lock timeout (seconds), used to acquire locks for table to validate, - default is 10 secs. 0 is no-wait, -1 is infinite wait. + default is 10 secs. 0 is no-wait, -1 is infinite wait. role: SQL ROLE name passed to gfix. callback: Function to call back with each output line. """ @@ -5276,8 +5275,6 @@ def upgrade(self, *, database: FILESPEC) -> bytes: Arguments: database: Database specification or alias. - flags: Repair flags. - role: SQL ROLE name passed to gfix. """ self._srv()._reset_output() with a.get_api().util.get_xpb_builder(XpbKind.SPB_START) as spb: @@ -5369,7 +5366,7 @@ def add(self, *, user_name: str, password: str, user_id: int | None=None, password: User password. user_id: User ID. group_id: Group ID. - firest_name: User's first name. + first_name: User's first name. middle_name: User's middle name. last_name: User's last name. admin: Admin flag. @@ -5414,7 +5411,7 @@ def update(self, user_name: str, *, password: str | None=None, password: User password. user_id: User ID. group_id: Group ID. - firest_name: User's first name. + first_name: User's first name. middle_name: User's middle name. last_name: User's last name. admin: Admin flag. @@ -5859,9 +5856,9 @@ def connect_server(server: str, *, user: str | None=None, password: str | None=N security database) role: SQL role used for connection. encoding: Encoding for string values passed in parameter buffer. Default is - `.ServerConfig.encoding`. + `.ServerConfig.encoding`. encoding_errors: Error handler used for encoding errors. Default is - `.ServerConfig.encoding_errors`. + `.ServerConfig.encoding_errors`. Hooks: Event `.ServerHook.ATTACHED`: Executed before `Service` instance is From add450d2fbfaa72e031c8af35fd84bf4c8fb2f46 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Fri, 23 Oct 2026 13:04:00 +0200 Subject: [PATCH 36/48] Fix pattern to detect Linux librarues --- src/firebird/driver/provider.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/firebird/driver/provider.py b/src/firebird/driver/provider.py index 940febd..b7b45c8 100644 --- a/src/firebird/driver/provider.py +++ b/src/firebird/driver/provider.py @@ -125,7 +125,7 @@ def _initialize(self, root: str, version: tuple[int, int]) -> None: if not root: raise RuntimeError('The Firebird client did not report a root directory') extension = 'dll' if sys.platform == 'win32' else 'so' - pattern = re.compile(rf'engine[0-9]+\.{extension}', re.IGNORECASE) + pattern = re.compile(rf'(?:lib)?engine[0-9]+\.{extension}', re.IGNORECASE) capabilities = {'client'} plugins = runtime_root / 'plugins' if plugins.is_dir() and any(pattern.fullmatch(path.name) for path in plugins.iterdir()): From 3b83ccd099101068f9986ce7178b3ce502c94356 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Fri, 23 Oct 2026 13:04:17 +0200 Subject: [PATCH 37/48] Test for previous fix --- tests/test_provider.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/tests/test_provider.py b/tests/test_provider.py index 6b985bd..5dd1ae3 100644 --- a/tests/test_provider.py +++ b/tests/test_provider.py @@ -1,5 +1,6 @@ """Runtime provider tests that do not need a Firebird installation.""" +import os from pathlib import Path from types import SimpleNamespace from unittest.mock import MagicMock @@ -54,7 +55,9 @@ def test_system_library_lookup(monkeypatch): @pytest.mark.parametrize(('plugin', 'embedded'), [ ('engine13.so', True), + ('libEngine13.so', True), ('engine.so', False), + ('libEngine13.so.bak', False), ('engine13.so.bak', False), ]) def test_metadata_from_loaded_client(tmp_path, plugin, embedded): @@ -100,6 +103,42 @@ def test_firebird_api_loads_supplied_provider(tmp_path, monkeypatch): api.provider = provider +@pytest.mark.parametrize('existing', [None, 'same', 'equivalent', 'different']) +def test_external_provider_sets_firebird_root_before_library_load(tmp_path, monkeypatch, existing): + root = tmp_path / 'runtime' + root.mkdir() + provider = SimpleNamespace(root=root, client_library=root / 'libfbclient.so') + current = {'same': str(root), + 'equivalent': str(root / '..' / 'runtime'), + 'different': str(tmp_path / 'other')}.get(existing) + if current is None: + monkeypatch.delenv('FIREBIRD', raising=False) + else: + monkeypatch.setenv('FIREBIRD', current) + seen = [] + monkeypatch.setattr(fbapi.ctypes, 'CDLL', lambda *_args, **_kwargs: + seen.append(os.environ.get('FIREBIRD')) or MagicMock()) + monkeypatch.setattr(fbapi, 'CFUNCTYPE', lambda *_args: lambda _: SimpleNamespace(argtypes=[])) + + fbapi.FirebirdAPI(provider=provider) + + expected = current if existing in ('same', 'equivalent') else str(root) + assert seen == [expected] + assert os.environ['FIREBIRD'] == expected + + +def test_driver_provider_does_not_change_firebird_root(tmp_path, monkeypatch): + library = tmp_path / 'libfbclient.so' + library.touch() + monkeypatch.setenv('FIREBIRD', str(tmp_path / 'configured')) + monkeypatch.setattr(fbapi.ctypes, 'CDLL', lambda *_args, **_kwargs: MagicMock()) + monkeypatch.setattr(fbapi, 'CFUNCTYPE', lambda *_args: lambda _: SimpleNamespace(argtypes=[])) + + fbapi.FirebirdAPI(provider=_DriverProvider(library)) + + assert os.environ['FIREBIRD'] == str(tmp_path / 'configured') + + def test_load_api_uses_external_provider(tmp_path, monkeypatch): provider = SimpleNamespace(client_library=tmp_path / 'fbclient.so') seen = [] From dc6c44363f68b59dd8463a646b96ced138af9caf Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Fri, 23 Oct 2026 13:05:39 +0200 Subject: [PATCH 38/48] Set FIREBIRD envar if needed --- src/firebird/driver/fbapi.py | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/src/firebird/driver/fbapi.py b/src/firebird/driver/fbapi.py index 2d5d94d..cb0aed0 100644 --- a/src/firebird/driver/fbapi.py +++ b/src/firebird/driver/fbapi.py @@ -39,6 +39,7 @@ import ctypes import decimal +import os import platform import sys from ctypes import ( @@ -1932,6 +1933,9 @@ class FirebirdAPI: locates a system client library. provider: Runtime provider supplied by keyword, as an alternative to `filename`. + When a runtime provider is supplied, `FIREBIRD` is set to its root before loading the + client library if the variable is unset or resolves to a different directory. + Attributes: provider (`.FirebirdProvider`): Runtime provider used to load this API client_library (`ctypes.CDLL`): Loaded Firebird client library `ctypes` handler @@ -2016,37 +2020,37 @@ class FirebirdAPI: isc_cancel_events(): Old API function. - isc_compile_request() + isc_compile_request(): Old API function. - isc_start_request() + isc_start_request(): Old API function. - isc_release_request() + isc_release_request(): Old API function. - isc_receive() + isc_receive(): Old API function. - isc_start_and_send() + isc_start_and_send(): Old API function. - isc_send() + isc_send(): Old API function. - isc_open_blob2() + isc_open_blob2(): Old API function. - isc_blob_info() + isc_blob_info(): Old API function. - isc_create_blob2() + isc_create_blob2(): Old API function. - isc_get_segment() + isc_get_segment(): Old API function. - isc_put_segment() + isc_put_segment(): Old API function. isc_close_blob(): @@ -2061,6 +2065,11 @@ def __init__(self, filename: FirebirdProvider | str | Path | None=None, selected = provider if provider is not None else filename self._provider = _DriverProvider(selected) if selected is None or isinstance(selected, (str, Path)) \ else selected + if not isinstance(self._provider, _DriverProvider): + runtime_root = Path(self._provider.root) + configured_root = os.environ.get('FIREBIRD') + if not configured_root or Path(configured_root).resolve() != runtime_root.resolve(): + os.environ['FIREBIRD'] = str(runtime_root) filename = self._provider.client_library self.client_library: ctypes.CDLL = None "Firebird client library" @@ -2243,6 +2252,9 @@ def load_api(filename: str | Path | FirebirdProvider | None=None) -> None: filename: Client library filename or runtime provider. When omitted, the configured filename is used, or the driver locates a system client library. + A supplied provider sets `FIREBIRD` to its root before loading the client library if + the variable is unset or resolves to a different directory. + Hooks: Event `HookType.HOOK_API_LOADED`: Executed after api is initialized. Hook routine must have signature: `hook_func(api)`. Any value returned by From 5692a300b7316b76f09848fbee070fdc0f3ada58 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Fri, 23 Oct 2026 13:05:55 +0200 Subject: [PATCH 39/48] Fix fixture --- tests/conftest.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index ed1f081..073a9bb 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -37,7 +37,6 @@ from pathlib import Path from importlib.metadata import entry_points -import os import platform from shutil import copyfile from configparser import ConfigParser @@ -143,7 +142,6 @@ def pytest_configure(config): driver_config.server_defaults.password.value = 'masterkey' # Select a bundled runtime before the first client API load or connection. if provider := _registered_provider(): - os.environ['FIREBIRD'] = str(provider.root) load_api(provider) api = get_api() _vars_['client-lib'] = api.client_library_name From 5c848e84fd4461bf15807be3a46ddcffcb40a2df Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Fri, 23 Oct 2026 13:06:27 +0200 Subject: [PATCH 40/48] Fix docstring --- src/firebird/driver/config.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/firebird/driver/config.py b/src/firebird/driver/config.py index 91a248a..1d709ce 100644 --- a/src/firebird/driver/config.py +++ b/src/firebird/driver/config.py @@ -214,9 +214,9 @@ def __init__(self, name: str): "Path to Firebird client library" self.stream_blob_threshold: IntOption = \ IntOption('stream_blob_threshold', - "BLOB size threshold. Bigger BLOB will be returned as stream BLOBs.", + "BLOB size threshold; larger BLOBs are streamed automatically (-1 disables it).", default=65536) - "BLOB size threshold. Bigger BLOB will be returned as stream BLOBs." + "BLOB size threshold. Larger BLOBs are streamed automatically; -1 disables this." self.db_defaults: DatabaseConfig = DatabaseConfig('firebird.db.defaults', optional=True, description="Default database configuration.") From f96259440c7fbce861c25bbddf1659e6d92eaf84 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Fri, 23 Oct 2026 13:44:54 +0200 Subject: [PATCH 41/48] Updated documentation --- development/README.md | 6 ++- development/core.md | 6 +++ development/fbapi.md | 7 ++- development/provider.md | 4 +- development/types.md | 1 + docs/docs/getting-started.md | 11 ++++ docs/docs/ref-core.md | 2 - docs/docs/ref-main.md | 5 +- docs/docs/ref-types.md | 5 ++ docs/docs/usage-guide/configuration.md | 41 +++++++++++---- .../data-handling-and-conversions.md | 3 +- .../docs/usage-guide/working-with-services.md | 52 ++++++++++++------- 12 files changed, 102 insertions(+), 41 deletions(-) diff --git a/development/README.md b/development/README.md index 2831229..d066203 100644 --- a/development/README.md +++ b/development/README.md @@ -42,8 +42,9 @@ wider suite when the prepared Firebird environment is available. Do not treat a or client library as a passing test. At startup, the tests inspect entry points in `firebird.runtime.providers`. With one provider, -they set `FIREBIRD` to its runtime root and load its client library before any connection; with -more than one, setup stops with an error. Without a registered provider, the configured or system +they load its client library before any connection. The driver sets `FIREBIRD` to the provider +root before loading the library if it is unset or points elsewhere. With more than one provider, +setup stops with an error. Without a registered provider, the configured or system client library is used. The pytest `Firebird:` header reports the loaded provider and the selected source database, which the fixtures copy for the run. The `fb3em` backend installs `firebird-embedded~=3.0`; check that its header reports Firebird 3 and `fbtest30.fdb`. @@ -62,6 +63,7 @@ from the major version alone when a feature was introduced in a minor release. Current test examples: snapshot-number and READ CONSISTENCY transaction parameters require Firebird 4.0 or newer; `SET DEBUG OPTION DSQL_KEEP_BLR` requires Firebird 4.0.1 or newer. +Trace session plugin selection requires Firebird 6.0 or newer. ## Documentation and packaging diff --git a/development/core.md b/development/core.md index 43709cf..bfda04a 100644 --- a/development/core.md +++ b/development/core.md @@ -7,6 +7,12 @@ This module implements the high-level DB API: `connect()`, `create_database()`, and service manager operations. It also builds parameter buffers and exposes version-sensitive information providers. +`Cursor.stream_blob_threshold = -1` disables automatic streaming by size; columns named in +`Cursor.stream_blobs` still use `BlobReader`. `Server.query_timeout` controls text output reads: +`readline()` and iteration return `TIMEOUT` without ending output, while `readlines()` omits +the sentinel. Trace session plugin selection through `ServerTraceServices.start(plugins=...)` +requires Firebird 6 or newer; older versions must omit that argument. + Keep resource ownership aligned with this structure. A `Connection` owns its transaction managers, statements, and event collectors; each `Cursor` holds its own transaction manager reference. The connection creates a main transaction, a read-only query transaction, and an internal cursor. diff --git a/development/fbapi.md b/development/fbapi.md index ddb4bd3..7834cbd 100644 --- a/development/fbapi.md +++ b/development/fbapi.md @@ -7,8 +7,11 @@ and the `FirebirdAPI` loader. `get_api()` calls `load_api()` on first use; the l is cached in the module. An explicit filename, provider instance, or `driver_config.fb_client_library.value` selects the client library before first load. Filenames are wrapped in the private driver provider; provider instances are used directly. The -`APIHook.LOADED` callbacks initialize the private provider after the master and utility -interfaces are available. +loader sets `FIREBIRD` to an external provider's root before loading its client library when +the variable is unset or resolves to another directory. It leaves an equivalent existing +path unchanged. The private driver provider has no root metadata until after loading, so +this automatic setup applies only to supplied providers. `APIHook.LOADED` callbacks initialize +the private provider after the master and utility interfaces are available. Changes to C layouts, pointer types, or signatures can affect every higher-level wrapper. Compare them with the supported Firebird client API and run focused integration tests on diff --git a/development/provider.md b/development/provider.md index 6d312d8..b0c3ad0 100644 --- a/development/provider.md +++ b/development/provider.md @@ -9,8 +9,8 @@ client API by the `interfaces.py` API-loaded hook. They must not be read before The runtime root comes from `IConfigManager.get_root_directory()`, not from the client filename. The private provider checks that root's `plugins` directory for a numbered `engineXX` shared -library to determine whether the embedded capability is present. External provider metadata -is not changed by the driver. +library to determine whether the embedded capability is present. The filename may have a `lib` +prefix, as in Linux `libEngine13.so`. External provider metadata is not changed by the driver. `firebird_log` is an optional local path in the public protocol. The private driver provider returns `None` because a client library does not identify the log of the server it connects to. diff --git a/development/types.md b/development/types.md index 9a293b1..bf5010e 100644 --- a/development/types.md +++ b/development/types.md @@ -6,6 +6,7 @@ This module defines DB API exception classes, Firebird protocol and information parameter block items, flags, dataclasses, and typing helpers. It also defines the DB API constants `apilevel`, `threadsafety`, and `paramstyle`, plus date/time constructors and type objects. Public selections are re-exported by `__init__.py`. +The `TIMEOUT` sentinel is defined here and exported from the main driver namespace. Keep numeric protocol values and flag combinations consistent with the Firebird client API. If a type or exception changes, check its use in `core.py` and `interfaces.py` and the relevant diff --git a/docs/docs/getting-started.md b/docs/docs/getting-started.md index 41fd67f..6bc4a19 100644 --- a/docs/docs/getting-started.md +++ b/docs/docs/getting-started.md @@ -40,6 +40,17 @@ necessary to adjust default configuration, or `register` them in configuration m You can manipulate the configuration objects directly, or load configuration from files or strings (in `.ini-style` `ConfigParser` format). +## Runtime providers + +**New in 2.1.0.** You can select a runtime provider before connecting to supply the client +library and its runtime files. Without an explicit provider, the driver uses its internal +provider for a configured or system client library. Once the API loads, `get_api().provider` +always returns an object implementing the +[`FirebirdProvider`](ref-provider.md#firebird.driver.provider.FirebirdProvider) protocol. See +[Runtime providers](usage-guide/configuration.md#runtime-providers) for selection +and setup, including the [firebird-embedded packages on PyPI](https://pypi.org/project/firebird-embedded/) +for Firebird 3, 4, and 5. + ## Connecting to a Database The examples use `employee`, the local alias for the Firebird sample database included diff --git a/docs/docs/ref-core.md b/docs/docs/ref-core.md index b6ce529..cae06ee 100644 --- a/docs/docs/ref-core.md +++ b/docs/docs/ref-core.md @@ -30,8 +30,6 @@ This is the main code module of the Firebird driver. ::: firebird.driver.core._util -::: firebird.driver.core.TIMEOUT - ## Context managers ::: firebird.driver.core.transaction diff --git a/docs/docs/ref-main.md b/docs/docs/ref-main.md index 12520b9..1473557 100644 --- a/docs/docs/ref-main.md +++ b/docs/docs/ref-main.md @@ -22,14 +22,13 @@ Functions: Translation dictionaries: `CHARSET_MAP` -Sentinels: - `TIMEOUT` - Classes: `Connection`, `Cursor`, `Server`, `Statement`, `TransactionManager`, `DistributedTransactionManager` and `TPB` ### types +Sentinels: + `TIMEOUT` Exceptions: `FirebirdWarning`, `Error`, `InterfaceError`, `DatabaseError`, `DataError`, diff --git a/docs/docs/ref-types.md b/docs/docs/ref-types.md index 1396be2..860494d 100644 --- a/docs/docs/ref-types.md +++ b/docs/docs/ref-types.md @@ -45,6 +45,11 @@ UserWarning |__FirebirdWarning ``` + +## Sentinels + +::: firebird.driver.types.TIMEOUT + ## Other constants and types required by Python DB API 2.0 specification ### Globals diff --git a/docs/docs/usage-guide/configuration.md b/docs/docs/usage-guide/configuration.md index 3140237..b6f97c5 100644 --- a/docs/docs/usage-guide/configuration.md +++ b/docs/docs/usage-guide/configuration.md @@ -28,14 +28,26 @@ configuration string, dict or file(s). calls any from following functions: [`connect()`](../ref-core.md#firebird.driver.core.connect), [`create_database()`](../ref-core.md#firebird.driver.core.create_database), [`connect_server()`](../ref-core.md#firebird.driver.core.connect_server), [`load_api()`](../ref-fbapi.md#firebird.driver.fbapi.load_api) or [`get_api()`](../ref-fbapi.md#firebird.driver.fbapi.get_api). -You can also call `load_api(provider)` with an instance of a runtime provider, such as one -advertised by the `firebird.runtime.providers` entry-point group. Entry points expose provider -classes; select and instantiate the desired class in your application. The driver does not -automatically choose an installed provider. The selected provider is available as the read-only -`get_api().provider` property. For an explicit filename or a system client, the driver uses its -own provider and obtains the runtime root and client version after loading the API. +!!! info + + [`DriverConfig`](../ref-config.md#firebird.driver.config.DriverConfig) for list of available methods and parameters. + +## Runtime providers + +**New in 2.1.0.** The driver can load a Firebird client library from an object implementing the +[`FirebirdProvider`](../ref-provider.md#firebird.driver.provider.FirebirdProvider) protocol. A +provider supplies the library path, runtime root, version, and capabilities. Pass a provider +instance to [`load_api(provider)`](../ref-fbapi.md#firebird.driver.fbapi.load_api) before the first +connection or other API load. The driver does not automatically select an installed provider. -For example, to select the `firebird-embedded` provider by entry-point name: +If no provider object is explicitly supplied, the driver uses its internal provider. It wraps +a filename passed to `load_api()` or set in `driver_config.fb_client_library`; otherwise it +locates a system client library. After the API loads successfully, +[`get_api().provider`](../ref-fbapi.md#firebird.driver.fbapi.FirebirdAPI.provider) always returns +an object implementing `FirebirdProvider`: the supplied instance or the internal provider. + +Providers may advertise themselves through the `firebird.runtime.providers` entry-point group. +The following example selects the `firebird-embedded` provider by entry-point name: ```python from importlib.metadata import entry_points @@ -43,12 +55,21 @@ from firebird.driver import load_api provider_entry = next(ep for ep in entry_points(group='firebird.runtime.providers') if ep.name == 'firebird') -load_api(provider_entry.load()()) +provider = provider_entry.load()() +load_api(provider) ``` -!!! info +When loading a supplied provider, the driver sets `FIREBIRD` to its root before loading the +client library if the variable is unset or points to another directory. An existing value +that resolves to the same directory is preserved. You do not need to set it in application +code. For an explicit library filename or a system client, the driver does not change +`FIREBIRD` because its runtime root is known only after the library loads. - [`DriverConfig`](../ref-config.md#firebird.driver.config.DriverConfig) for list of available methods and parameters. +!!! tip "Embedded Firebird runtimes" + + [firebird-embedded packages on PyPI](https://pypi.org/project/firebird-embedded/) provide + embedded runtimes for Firebird 3, 4, and 5. Install the major version you need, then select + its provider before connecting. ## Server and database configuration diff --git a/docs/docs/usage-guide/data-handling-and-conversions.md b/docs/docs/usage-guide/data-handling-and-conversions.md index 1d61021..f6b1d5a 100644 --- a/docs/docs/usage-guide/data-handling-and-conversions.md +++ b/docs/docs/usage-guide/data-handling-and-conversions.md @@ -185,7 +185,8 @@ These drawbacks are addressed by `stream` BLOBs. Using BLOBs in `stream` mode is string/bytes value. Zero threshold value effectively forces all blobs to be returned as stream blobs. - Negative value means no size limit for materialized blobs (use at your own risk). + A threshold of `-1` disables automatic streaming by size, leaving no size limit for + materialized blobs (use at your own risk). Other negative values do not disable it. Please note that positive threshold value means that your application has to be prepared to handle BLOBs in both incarnations. diff --git a/docs/docs/usage-guide/working-with-services.md b/docs/docs/usage-guide/working-with-services.md index 69f8623..77ff94a 100644 --- a/docs/docs/usage-guide/working-with-services.md +++ b/docs/docs/usage-guide/working-with-services.md @@ -121,9 +121,9 @@ Some services like [`ServerDbServices.backup()`](../ref-core.md#firebird.driver. Rather than return the whole text as single string value by methods that provide access to these services, firebird-driver isolated the transfer process to separate methods: -* [`readline()`](../ref-core.md#firebird.driver.core.Server.readline) - Similar to `file.readline`, returns next line of output from Service. -* [`readline_timed()`](../ref-core.md#firebird.driver.core.Server.readline_timed) - Like [`readline()`](../ref-core.md#firebird.driver.core.Server.readline) but with timeout. -* [`readlines()`](../ref-core.md#firebird.driver.core.Server.readlines) - Like `file.readlines`, returns list of output lines. +* [`readline()`](../ref-core.md#firebird.driver.core.Server.readline) - Returns the next line, `None` at end of output, or [`TIMEOUT`](../ref-types.md#firebird.driver.types.TIMEOUT) when `query_timeout` expires. +* [`readline_timed()`](../ref-core.md#firebird.driver.core.Server.readline_timed) - Queries one line with an explicit timeout for that call. +* [`readlines()`](../ref-core.md#firebird.driver.core.Server.readlines) - Returns the remaining lines, omitting timeout signals. * Iteration over [`Server`](../ref-core.md#firebird.driver.core.Server) object, because [`Server`](../ref-core.md#firebird.driver.core.Server) has built-in support for [iterator protocol](https://docs.python.org/3/library/stdtypes.html#iterator-types). * Using `callback` method provided by developer. Each [`Server`](../ref-core.md#firebird.driver.core.Server) method that returns its result asynchronously accepts an optional parameter `callback`, which must be a function that accepts @@ -160,14 +160,28 @@ to these services, firebird-driver isolated the transfer process to separate met !!! important - Normally, requesting output with [`readline()`](../ref-core.md#firebird.driver.core.Server.readline) blocks until any output is - available from server. Bacuse this method is used by iteration over [`Server`](../ref-core.md#firebird.driver.core.Server) and - [`readlines()`](../ref-core.md#firebird.driver.core.Server.readlines) method, they will block as well. Most services produce output - continuously and without (much) delay, so this is usually not a problem. However, some - services (eg trace) can produce output at significantly slower intervals (if at all), - which complicates the creation of responsive applications. In this case, it is necessary - to use the [`readline_timed()`](../ref-core.md#firebird.driver.core.Server.readline_timed) method, which allows you to limit the waiting - time for the output. + [`Server.query_timeout`](../ref-core.md#firebird.driver.core.Server) defaults to `-1`, so + [`readline()`](../ref-core.md#firebird.driver.core.Server.readline) and iteration wait for + output indefinitely. Set it to a positive number of seconds for a service that may be quiet, + such as trace. On timeout, `readline()` and iteration return the `TIMEOUT` sentinel without + ending the stream; the next read can still receive output. `readlines()` skips timeout + signals and continues until the service output ends. `readline_timed(timeout)` remains + available when a single line query needs its own timeout. + +```python +from firebird.driver import TIMEOUT + +srv.query_timeout = 2 +line = srv.readline() +if line is TIMEOUT: + # No output arrived yet; the stream remains open. + pass +elif line is None: + # End of output. + pass +else: + print(line) +``` **Examples:** @@ -178,13 +192,13 @@ with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: print("==================") print("Start backup") srv.database.backup(database='employee', backup='employee.fbk') - print("srv.running is", srv.isrunning()) + print("srv.running is", srv.is_running()) report = srv.readlines() print(f"{len(report)} lines returned") print("First 5 lines from output:") - for i in xrange(5): + for i in range(min(5, len(report))): print(i,report[i]) - print("srv.running is", srv.isrunning()) + print("srv.running is", srv.is_running()) print() print("Iterate over result") print("===================") @@ -220,7 +234,7 @@ Output: Fetch materialized ================== Start backup -svc.running is True +srv.running is True 558 lines returned First 5 lines from output: 0 gbak:readied database employee for backup @@ -228,7 +242,7 @@ First 5 lines from output: 2 gbak:starting transaction 3 gbak:database employee has a page size of 4096 bytes. 4 gbak:writing domains -svc.running is False +srv.running is False Iterate over result =================== @@ -625,7 +639,7 @@ Database options could be set using [`ServerDbServices`](../ref-core.md#firebird The [`Server.trace`](../ref-core.md#firebird.driver.core.Server.trace) property provides access to instance of [`ServerTraceServices`](../ref-core.md#firebird.driver.core.ServerTraceServices) or its **ancestor** class according to attached Firebird server version. -* [`ServerTraceServices.start()`](../ref-core.md#firebird.driver.core.ServerTraceServices.start) - Start new trace session. Requires trace `configuration` and returns `Session ID`. +* [`ServerTraceServices.start()`](../ref-core.md#firebird.driver.core.ServerTraceServices.start) - Start a trace session with a `config` string and optional `name`. On Firebird 6 or newer, `plugins` accepts a plugin name or a list of names. Returns the session ID. This method is so-called `Async service` that only starts the trace session. Output from trace session could be read by one from many methods for [text output from Services](working-with-services.md#text-output-from-services) @@ -647,7 +661,7 @@ Database options could be set using [`ServerDbServices`](../ref-core.md#firebird """ with connect_server('localhost', user='SYSDBA', password='masterkey') as srv: - trace_id = srv.trace.start(trace_config,'test_trace_1') + trace_id = srv.trace.start(config=trace_config, name='test_trace_1') trace_log = [] # Get first 10 lines of trace output for i in range(10): @@ -665,4 +679,4 @@ Database options could be set using [`ServerDbServices`](../ref-core.md#firebird * [`ServerTraceServices.resume()`](../ref-core.md#firebird.driver.core.ServerTraceServices.resume) - Resume trace session. -* [`ServerTraceServices.sessions`](../ref-core.md#firebird.driver.core.ServerTraceServices.sessions) - Dictionary with active trace sessions. The key is session ID, value is [`TraceSession`](../ref-types.md#firebird.driver.types.TraceSession) instance. +* [`ServerTraceServices.sessions`](../ref-core.md#firebird.driver.core.ServerTraceServices.sessions) - Dictionary with active trace sessions. The key is session ID, value is a [`TraceSession`](../ref-types.md#firebird.driver.types.TraceSession) instance. Its `plugins` list contains the plugin names reported by the service manager, when available. From 10ef4391177d53b85a6f682d3bc15b7899004920 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Fri, 23 Oct 2026 14:00:56 +0200 Subject: [PATCH 42/48] Skilll packaging workflow --- pyproject.toml | 5 +++-- scripts/build_skill.py | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 scripts/build_skill.py diff --git a/pyproject.toml b/pyproject.toml index d5f6833..a5f1c72 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -57,6 +57,9 @@ allow-direct-references = true dependencies = [ ] +[tool.hatch.envs.default.scripts] +build-skill = "python scripts/build_skill.py" + [tool.hatch.envs.hatch-test] extra-dependencies = [ "packaging>=25.0", @@ -64,10 +67,8 @@ extra-dependencies = [ [[tool.hatch.envs.hatch-test.matrix]] python = ["3.11", "3.12", "3.13", "3.14", "3.15"] -#backend = ["local", "localem"] backend = ["local", "localem", "fb3em", "fb4em", "fb5em"] - [tool.hatch.envs.hatch-test.overrides] matrix.backend.extra-args = { value = ["--host=localhost"], if = ["local"] } matrix.backend.extra-dependencies = [ diff --git a/scripts/build_skill.py b/scripts/build_skill.py new file mode 100644 index 0000000..da245b8 --- /dev/null +++ b/scripts/build_skill.py @@ -0,0 +1,37 @@ +"""Package the firebird-driver-python agent skill for distribution.""" + +import ast +from pathlib import Path +from zipfile import ZIP_DEFLATED, ZipFile + + +def driver_version(root: Path) -> str: + """Read the version without importing the driver or loading a Firebird client.""" + version_file = root / "src" / "firebird" / "driver" / "__init__.py" + for node in ast.parse(version_file.read_text(encoding="utf-8")).body: + if isinstance(node, ast.Assign) and any( + isinstance(target, ast.Name) and target.id == "__VERSION__" for target in node.targets + ): + version = ast.literal_eval(node.value) + if isinstance(version, str): + return version + raise ValueError(f"No literal __VERSION__ found in {version_file}") + + +def main() -> None: + """Write a ZIP with the skill directory at its root.""" + root = Path(__file__).resolve().parent.parent + skill = root / "skills" / "firebird-driver-python" + if not (skill / "SKILL.md").is_file(): + raise FileNotFoundError(skill / "SKILL.md") + archive_path = root / "dist" / f"firebird-driver-{driver_version(root)}-skill.zip" + archive_path.parent.mkdir(exist_ok=True) + + with ZipFile(archive_path, "w", compression=ZIP_DEFLATED) as archive: + for path in sorted(skill.rglob("*")): + if path.is_file(): + archive.write(path, path.relative_to(skill.parent)) + + +if __name__ == "__main__": + main() From 9def9e57a585ee3682f1e34ebd2243047371c4ba Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Fri, 23 Oct 2026 14:01:24 +0200 Subject: [PATCH 43/48] Updated documentation --- README.md | 35 ++++++++++------------------------- development/README.md | 2 ++ docs/docs/index.md | 6 ++++++ 3 files changed, 18 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 659a57a..2d2e6e4 100644 --- a/README.md +++ b/README.md @@ -37,37 +37,22 @@ to this driver. ## Agent skill This repository includes a [skill for coding with firebird-driver](skills/firebird-driver-python/SKILL.md). -Once the skill is published on GitHub, run these commands in a directory where -you want to keep a checkout (Unix-like shell): +For releases that include the skill archive, download `firebird-driver--skill.zip` +from [GitHub Releases](https://github.com/FirebirdSQL/python3-driver/releases). Choose the +release matching the driver version you use. The ZIP contains the complete +`firebird-driver-python/` directory, including `SKILL.md` and `references/`. Extract it into +`~/.codex/skills/` for Codex, `~/.claude/skills/` for Claude Code, or `~/.gemini/skills/` for +Gemini CLI. + +To install from the repository instead, run these commands in a directory where you want to +keep a checkout (Unix-like shell): ```sh git clone --depth 1 --filter=blob:none --sparse https://github.com/FirebirdSQL/python3-driver.git firebird-driver-skill-source git -C firebird-driver-skill-source sparse-checkout set skills/firebird-driver-python ``` -Then copy the skill into the directory for each agent you use: - -```sh -# Codex -mkdir -p ~/.codex/skills -cp -R firebird-driver-skill-source/skills/firebird-driver-python ~/.codex/skills/ - -# Claude Code -mkdir -p ~/.claude/skills -cp -R firebird-driver-skill-source/skills/firebird-driver-python ~/.claude/skills/ - -# Gemini CLI -mkdir -p ~/.gemini/skills -cp -R firebird-driver-skill-source/skills/firebird-driver-python ~/.gemini/skills/ -``` - -Run only the copy commands for the agents you use. Each user-level location makes -the skill available across your projects. Codex lists installed skills with -`/skills`; Claude Code can invoke `/firebird-driver-python`; Gemini CLI lists -them with `/skills list` and can reload them with `/skills reload`. -See the [Codex](https://learn.chatgpt.com/docs/build-skills), -[Claude Code](https://code.claude.com/docs/en/skills), and -[Gemini CLI](https://geminicli.com/docs/cli/using-agent-skills/) skill guides. +Then copy the skill into the directory for each agent you use. ## License diff --git a/development/README.md b/development/README.md index d066203..28c967c 100644 --- a/development/README.md +++ b/development/README.md @@ -75,3 +75,5 @@ publish the Zensical output. Keep user-facing API descriptions in source docstri The project builds with Hatchling. The version comes from `src/firebird/driver/__init__.py`, and Ruff settings are in `pyproject.toml`. +Run `hatch run build-skill` to package the complete `skills/firebird-driver-python/` directory +as `dist/firebird-driver--skill.zip` for a GitHub release. diff --git a/docs/docs/index.md b/docs/docs/index.md index e2a1ad8..412493f 100644 --- a/docs/docs/index.md +++ b/docs/docs/index.md @@ -33,3 +33,9 @@ written by Helen Borrie and published by [IBPhoenix](http://www.ibphoenix.com). You can download docset for [Dash](https://kapeli.com/dash) (MacOS) or [Zeal](https://zealdocs.org/) (Windows / Linux) documentation readers from [releases](https://github.com/FirebirdSQL/python3-driver/releases) at github. + +## Agent skill + +The firebird-driver agent skill provides guidance for using individual modules. Download +`firebird-driver--skill.zip` from [GitHub Releases](https://github.com/FirebirdSQL/python3-driver/releases) +and extract its `firebird-driver/` directory into your coding agent's skills directory. From ce953743b030b276ca3cb80b842a141df7ee3cb0 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Fri, 23 Oct 2026 14:17:04 +0200 Subject: [PATCH 44/48] Promote version; updated changelog --- CHANGELOG.md | 19 ++++++++++++++++--- docs/zensical.toml | 2 +- src/firebird/driver/__init__.py | 2 +- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ec1136d..671749c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,18 +4,20 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). -## Development +## [2.1.0] - 2026-10-23 ### Added - A runtime provider protocol and provider-based client library selection through `load_api()`. -- An optional `FirebirdProvider.firebird_log` path for runtimes with a directly accessible log. + `get_api().provider` exposes the selected provider or the driver's internal provider. - Firebird 6 trace session plugin support: `ServerTraceServices.start()` accepts plugin names, and `TraceSession` reports the plugins returned by the service manager. - Configurable `Server.query_timeout` and a `TIMEOUT` sentinel for timed text output queries. `readline()` and iteration report timeouts without ending output; `readlines()` omits them. - Generated `llms.txt` for the published documentation and a repository skill for coding with `firebird-driver`. +- A `hatch run build-skill` workflow that packages the complete skill as a versioned ZIP for + GitHub Releases. - Developer guidance in `development/`, including module notes and test and build instructions. ### Changed @@ -23,20 +25,31 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Migrated the user documentation and Read the Docs build from Sphinx to Zensical, including the API reference and docset workflow. - Split the usage guide into topic pages and corrected examples, links, and API descriptions. -- Updated repository funding information and removed the unused `gdocs` build environment. +- Improved API reference rendering for class attributes and type annotations, and added + light and dark documentation themes. +- Removed the unused `gdocs` build environment. +- Declared Python 3.14 and 3.15 in package classifiers and added 3.15 to the test matrix. - Added Firebird 3, 4, and 5 embedded test backends with provider selection and runtime details in the pytest session header. +- **BREAKING CHANGE**: Corrected `keyhoder` to `keyholder` in `backup()`, `restore()`, + `local_backup()`, and `local_restore()`; the misspelled keyword is no longer accepted. - Documented version guards for Firebird features introduced in separate minor releases of supported branches. ### Fixed - Decode `iUtil.get_client_version()` into major and minor version numbers. +- Avoid caching a partially initialized client API when an API-loaded hook fails. +- GH-70: Preserve buffered service output lines after a non-LF line boundary in + `Server.readline()`. +- Treat `stream_blob_threshold=-1` as disabling automatic BLOB streaming. +- Detect Linux `libEngineXX.so` plugins when reporting the internal provider's embedded capability. - GH-69: Avoid detaching an already released Firebird 5 attachment during garbage collection. - Keep the trace session `plugins` argument optional for existing callers. - Correct historical changelog issue references and links for Markdown rendering in Zensical. - Allow server log tests to pass when the log exists but has no entries. - Isolate connection hooks between tests and close the connection supplied by the attach hook test. +- Make the local backup integration test work across supported Firebird versions. - Make Firebird 3 integration tests respect feature availability, roll back failed fixture cleanup, and avoid timing assumptions for short service actions. diff --git a/docs/zensical.toml b/docs/zensical.toml index 0662ed3..2d835aa 100644 --- a/docs/zensical.toml +++ b/docs/zensical.toml @@ -72,7 +72,7 @@ find_stubs_package = true [project.plugins.llmstxt] enabled = true -markdown_description = "For driver version 2.1.0.dev0" +markdown_description = "For driver version 2.1.0" sections = { "Usage Guide" = [ "usage-guide/driver-structure.md" , diff --git a/src/firebird/driver/__init__.py b/src/firebird/driver/__init__.py index 036b335..3467a7d 100644 --- a/src/firebird/driver/__init__.py +++ b/src/firebird/driver/__init__.py @@ -134,5 +134,5 @@ TIMEOUT, ) -__VERSION__ = '2.1.0.dev0' +__VERSION__ = '2.1.0' "Current driver version, SEMVER string." From 5f5628215da4281176ccb1b11beb369ada99211f Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Thu, 29 Oct 2026 12:18:21 +0100 Subject: [PATCH 45/48] Fix for #75 Avoid native cleanup from connection, transaction, statement, cursor, BLOB reader, and interface finalizers after a database connection is lost. --- CHANGELOG.md | 7 ++ development/core.md | 6 ++ development/interfaces.md | 5 ++ src/firebird/driver/__init__.py | 2 +- src/firebird/driver/core.py | 28 +++++-- src/firebird/driver/interfaces.py | 26 ++++-- tests/test_connection_lifecycle.py | 125 +++++++++++++++++++++++++++++ 7 files changed, 185 insertions(+), 14 deletions(-) create mode 100644 tests/test_connection_lifecycle.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 671749c..0966a24 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [2.1.1.dev0] - Unreleased development version + +### Fixed + +- GT-75: Cursor, Statement, and Connection finalizers raise unraisable DatabaseError after + connection loss + ## [2.1.0] - 2026-10-23 ### Added diff --git a/development/core.md b/development/core.md index bfda04a..e13f1e4 100644 --- a/development/core.md +++ b/development/core.md @@ -20,6 +20,12 @@ Closing a connection must account for its dependent resources. The `transaction( manager begins a transaction and commits or rolls back on exit; with `bypass=True`, it joins an already active transaction without finishing it. +Connection, transaction manager, statement, cursor, and BLOB reader finalizers share the +connection's lifecycle flag. When a connection-loss status marks it dead, their finalizers skip +native cleanup. Result set and BLOB interfaces created from an attachment or statement inherit +the same flag, so errors during fetch or BLOB reads mark the owning connection. +Distributed transaction finalizers check the flags of every participating connection. + For changes here, select tests by behavior: `test_connection.py`, `test_transaction.py`, `test_cursor.py`, `test_statement.py`, `test_blob.py`, `test_array.py`, `test_events.py`, `test_distributed_trans.py`, `test_server.py`, and `test_info_providers.py`. Exercise the real diff --git a/development/interfaces.md b/development/interfaces.md index 340c5f7..1c57fd1 100644 --- a/development/interfaces.md +++ b/development/interfaces.md @@ -15,3 +15,8 @@ the matching `fbapi.py` declarations and run integration tests for the Firebird they affect. The same hook completes metadata for the private driver provider using the root directory and client version reported by the loaded API. `iUtil.get_client_version()` returns `(major, minor)`. + +Attachment, transaction, statement, result set, and BLOB wrappers propagate the owning +connection's lifecycle flag. Status errors for `isc_conn_lost`, `isc_net_read_err`, +`isc_net_write_err`, `isc_lost_db_connection`, and `isc_att_shutdown` mark that flag dead. +Reference-counted finalizers skip native release when it is dead. diff --git a/src/firebird/driver/__init__.py b/src/firebird/driver/__init__.py index 3467a7d..2da3f14 100644 --- a/src/firebird/driver/__init__.py +++ b/src/firebird/driver/__init__.py @@ -134,5 +134,5 @@ TIMEOUT, ) -__VERSION__ = '2.1.0' +__VERSION__ = '2.1.1.dev0' "Current driver version, SEMVER string." diff --git a/src/firebird/driver/core.py b/src/firebird/driver/core.py index 09e91ee..8d848a7 100644 --- a/src/firebird/driver/core.py +++ b/src/firebird/driver/core.py @@ -381,6 +381,10 @@ def temp_database(*args, **kwargs) -> Connection: _OP_DIE = object() _OP_RECORD_AND_REREGISTER = object() +class ConnectionLifecycle: + def __init__(self): + self.is_dead = False + # Managers for Parameter buffers class TPB: """Helper class to build and parse Transaction Parameter Buffers (TPB) used when starting transactions. @@ -1760,7 +1764,9 @@ class Connection: NotSupportedError = NotSupportedError def __init__(self, att: iAttachment, dsn: str, dpb: bytes | None=None, sql_dialect: int=3, charset: str | None=None) -> None: + self._lifecycle = ConnectionLifecycle() self._att: iAttachment = att + self._att._lifecycle = self._lifecycle self.__handle: a.FB_API_HANDLE = None self.__str: str = f'Connection[{self._get_handle().value}]' self.__charset: str = charset @@ -1780,20 +1786,19 @@ def __init__(self, att: iAttachment, dsn: str, dpb: bytes | None=None, sql_diale self.__ev: float = None self.__info: DatabaseInfoProvider = None self._tra_main: TransactionManager = TransactionManager(self, self.default_tpb) - self._tra_main._logging_id_ = 'Transaction.Main' self._tra_qry: TransactionManager = TransactionManager(self, tpb(Isolation.READ_COMMITTED_RECORD_VERSION, access_mode=TraAccessMode.READ)) - self._tra_qry._logging_id_ = 'Transaction.Query' # Cursor for internal use self._ic = self.query_transaction.cursor() self._ic._connection = weakref.proxy(self, self._ic._dead_con) - self._ic._logging_id_ = 'Cursor.internal' # firebird.lib extensions self.__schema = None self.__monitor = None self.__FIREBIRD_LIB__ = None def __del__(self): + if getattr(getattr(self, '_lifecycle', None), 'is_dead', False): + return if not self.is_closed(): warn("Connection disposed without prior close()", ResourceWarning) self._close() @@ -2590,6 +2595,7 @@ class TransactionManager: def __init__(self, connection: Connection, default_tpb: bytes, default_action: DefaultAction=DefaultAction.COMMIT): self._connection: Callable[[], Connection] = weakref.ref(connection, self.__dead_con) + self._lifecycle = connection._lifecycle self.default_tpb: bytes = default_tpb "Default Transaction Parameter Block used to start transaction" self.default_action: DefaultAction = default_action @@ -2599,13 +2605,16 @@ def __init__(self, connection: Connection, default_tpb: bytes, self._cursors: list = [] # Weak references to cursors self._tra: iTransaction = None self.__closed: bool = False - self._logging_id_ = 'Transaction' def __enter__(self) -> Self: self.begin() return self def __exit__(self, exc_type, exc_value, traceback) -> None: self.close() def __del__(self): + if getattr(getattr(self, '_lifecycle', None), 'is_dead', False): + return + if any(lifecycle.is_dead for lifecycle in getattr(self, '_lifecycles', ())): + return if self._tra is not None: warn("Transaction disposed while active", ResourceWarning) self._finish() @@ -2766,13 +2775,13 @@ class DistributedTransactionManager(TransactionManager): def __init__(self, connections: Sequence[Connection], default_tpb: bytes | None=None, default_action: DefaultAction=DefaultAction.COMMIT): self._connections: list[Connection] = list(connections) + self._lifecycles = tuple(con._lifecycle for con in self._connections) self.default_tpb: bytes = default_tpb if default_tpb is not None else tpb(Isolation.SNAPSHOT) self.default_action: DefaultAction = default_action self._cursors: list = [] # Weak references to cursors self._tra: iTransaction = None self._dtc: iDtc = _master.get_dtc() self.__closed: bool = False - self._logging_id_ = 'DTransaction' def close(self) -> None: """Close the distributed transaction manager and release all associated resources. @@ -2978,6 +2987,7 @@ class Statement: """ def __init__(self, connection: Connection, stmt: iStatement, sql: str, dialect: int): self._connection: Callable[[], Connection] = weakref.ref(connection, self.__dead_con) + self._lifecycle = connection._lifecycle self._dialect: int = dialect self.__sql: str = sql self._istmt: iStatement = stmt @@ -3016,6 +3026,8 @@ def __enter__(self) -> Self: def __exit__(self, exc_type, exc_value, traceback) -> None: self.free() def __del__(self): + if getattr(getattr(self, '_lifecycle', None), 'is_dead', False): + return if self._in_meta or self._out_meta or self._istmt: warn("Statement disposed without prior free()", ResourceWarning) self.free() @@ -3116,6 +3128,7 @@ class BlobReader(io.IOBase): def __init__(self, blob: iBlob, blob_id: a.ISC_QUAD, sub_type: int, length: int, segment_size: int, charset: str, owner: Any | None=None): self._blob: iBlob = blob + self._lifecycle = blob._lifecycle self.newline: str = '\n' self.sub_type: int = sub_type self._owner: Any | None = weakref.ref(owner) @@ -3150,6 +3163,8 @@ def __enter__(self) -> BlobReader: def __exit__(self, exc_type, exc_value, traceback) -> None: self.close() def __del__(self): + if getattr(getattr(self, '_lifecycle', None), 'is_dead', False): + return if self._blob is not None: warn("BlobReader disposed without prior close()", ResourceWarning) self.close() @@ -3330,6 +3345,7 @@ class Cursor: "This read/write attribute specifies the number of rows to fetch at a time with\n.fetchmany(). It defaults to 1 meaning to fetch a single row at a time.\n\nRequired by Python DB API 2.0" def __init__(self, connection: Connection, transaction: TransactionManager): self._connection: Connection = connection + self._lifecycle = connection._lifecycle self._dialect: int = connection.sql_dialect self._transaction: TransactionManager = transaction self._stmt: Statement = None @@ -3351,6 +3367,8 @@ def __enter__(self) -> Self: def __exit__(self, exc_type, exc_value, traceback) -> None: self.close() def __del__(self): + if getattr(getattr(self, '_lifecycle', None), 'is_dead', False): + return if self._result is not None or self._stmt is not None or self.__blob_readers: warn("Cursor disposed without prior close()", ResourceWarning) self.close() diff --git a/src/firebird/driver/interfaces.py b/src/firebird/driver/interfaces.py index b3d60e3..90ec340 100644 --- a/src/firebird/driver/interfaces.py +++ b/src/firebird/driver/interfaces.py @@ -115,6 +115,10 @@ def __init__(self, intf): self._as_parameter_ = intf if intf and self.vtable.version < self.VERSION: # pragma: no cover raise InterfaceError(f"Wrong interface version {self.vtable.version}, expected {self.VERSION}") + def _with_lifecycle(self, result): + if hasattr(self, '_lifecycle'): + result._lifecycle = self._lifecycle + return result def __report(self, cls: Error | FirebirdWarning, vector_ptr: a.ISC_STATUS_ARRAY_PTR) -> None: msg = _util.format_status(self.status) sqlstate = create_string_buffer(6) @@ -133,6 +137,12 @@ def __report(self, cls: Error | FirebirdWarning, vector_ptr: a.ISC_STATUS_ARRAY_ i += 1 # We need to clean up the iStatus before returning self.status.init() + # Check for connection shutdown/loss codes + if any(code in {335544856, 335544726, 335544727, 335544648, 335544741} + for code in gds_codes): + # If a back-channel lifecycle reference was injected, flip it! + if hasattr(self, '_lifecycle'): + self._lifecycle.is_dead = True return cls(msg, sqlstate=sqlstate.value.decode(), gds_codes=tuple(gds_codes), sqlcode=sqlcode,) def _check(self) -> None: @@ -167,7 +177,7 @@ def __init__(self, intf): super().__init__(intf) self._refcnt: int = 1 def __del__(self): - if self._refcnt > 0: + if self._refcnt > 0 and not getattr(getattr(self, '_lifecycle', None), 'is_dead', False): self.release() def __enter__(self) -> iReferenceCounted: return self @@ -819,7 +829,7 @@ def open_cursor(self, transaction: iTransaction, in_meta: iMessageMetadata, in_b value to IStatement::CURSOR_TYPE_SCROLLABLE.""" result = self.vtable.openCursor(self, self.status, transaction, in_meta, in_buffer, out_meta, flags) self._check() - return iResultSet(result) + return self._with_lifecycle(iResultSet(result)) def set_cursor_name(self, name: str) -> None: "Replaces `isc_dsql_set_cursor_name()`" self.vtable.setCursorName(self, self.status, name.encode()) @@ -1110,13 +1120,13 @@ def start_transaction(self, tpb: bytes) -> iTransaction: transactions into single distributed transaction""" result = self.vtable.startTransaction(self, self.status, len(tpb), tpb) self._check() - return iTransaction(result) + return self._with_lifecycle(iTransaction(result)) def reconnect_transaction(self, id_: bytes) -> iTransaction: """Makes it possible to connect to a transaction in limbo. Id parameter contains transaction number in network format of given length.""" result = self.vtable.reconnectTransaction(self, self.status, len(id_), id_) self._check() - return iTransaction(result) + return self._with_lifecycle(iTransaction(result)) def compile_request(self, blr: bytes) -> iRequest: "Support of ISC API" result = self.vtable.compileRequest(self, self.status, len(blr), blr) @@ -1132,13 +1142,13 @@ def create_blob(self, transaction: iTransaction, id_: a.ISC_QUAD, bpb: bytes | N result = self.vtable.createBlob(self, self.status, transaction, byref(id_), len(bpb) if bpb is not None else 0, bpb) self._check() - return iBlob(result) + return self._with_lifecycle(iBlob(result)) def open_blob(self, transaction: iTransaction, id_: a.ISC_QUAD, bpb: bytes | None=None) -> iBlob: "Opens existing blob, replaces `isc_open_blob2()`" result = self.vtable.openBlob(self, self.status, transaction, byref(id_), len(bpb) if bpb is not None else 0, bpb) self._check() - return iBlob(result) + return self._with_lifecycle(iBlob(result)) def get_slice(self, transaction: iTransaction, id_: a.ISC_QUAD, sdl: bytes, param: bytes, slice_: bytes) -> int: "Support of ISC API" @@ -1165,7 +1175,7 @@ def prepare(self, transaction: iTransaction, stmt: str, dialect: int, result = self.vtable.prepare(self, self.status, transaction, len(b_stmt), b_stmt, dialect, flags) self._check() - return iStatement(result) + return self._with_lifecycle(iStatement(result)) def execute(self, transaction: iTransaction, stmt: str, dialect: int, in_metadata: iMessageMetadata | None=None, in_buffer: bytes | None=None, out_metadata: iMessageMetadata | None=None, out_buffer: bytes | None=None) -> None: @@ -1191,7 +1201,7 @@ def open_cursor(self, transaction: iTransaction, stmt: str, dialect: int, dialect, in_metadata, in_buffer, out_metadata, cursor_name.encode(self.encoding), cursor_flags) self._check() - return iResultSet(result) + return self._with_lifecycle(iResultSet(result)) def que_events(self, callback: iEventCallbackImpl, events: bytes) -> iEvents: """Replaces `isc_que_events()` call. Instead callback function with void* parameter callback interface is used.""" diff --git a/tests/test_connection_lifecycle.py b/tests/test_connection_lifecycle.py new file mode 100644 index 0000000..c5534a0 --- /dev/null +++ b/tests/test_connection_lifecycle.py @@ -0,0 +1,125 @@ +# SPDX-FileCopyrightText: 2025-present The Firebird Projects +# +# SPDX-License-Identifier: MIT + +from contextlib import ExitStack, contextmanager +from ctypes import c_long +from io import StringIO +from unittest.mock import Mock, PropertyMock, patch + +import pytest + +from firebird.driver import DatabaseError, DistributedTransactionManager, connect, interfaces +from firebird.driver.types import StateFlag + + +@contextmanager +def error_status(code): + status = Mock() + status.get_state.return_value = StateFlag.ERRORS + status.get_errors.return_value = (c_long * 3)(1, code, 0) + with ExitStack() as stack: + stack.enter_context(patch.object(interfaces.iVersioned, 'status', + new_callable=PropertyMock, return_value=status)) + stack.enter_context(patch.object(interfaces._util, 'format_status', + return_value='database error')) + stack.enter_context(patch.object(interfaces.a.api, 'fb_sqlstate', + side_effect=lambda buf, _vector: setattr(buf, 'value', b'08006'))) + stack.enter_context(patch.object(interfaces.a.api, 'isc_sqlcode', return_value=-902)) + yield + + +@pytest.mark.parametrize('code', [335544648, 335544726, 335544727, + 335544741, 335544856]) +def test_connection_loss_status_marks_lifecycle(dsn, code): + with connect(dsn) as con: + with error_status(code): + with pytest.raises(DatabaseError) as exc: + con._att._check() + assert code in exc.value.gds_codes + assert con._lifecycle.is_dead + assert con._att._lifecycle is con._lifecycle + con._lifecycle.is_dead = False + + +def test_other_status_does_not_mark_lifecycle(dsn): + with connect(dsn) as con: + with error_status(335544569): + with pytest.raises(DatabaseError): + con._att._check() + assert not con._lifecycle.is_dead + + +def test_result_and_blob_interfaces_share_connection_lifecycle(dsn): + with connect(dsn) as con: + with connect(dsn) as other: + assert other._lifecycle is not con._lifecycle + assert other._att._lifecycle is other._lifecycle + with con.cursor() as cur: + cur.execute('insert into T2 (C1,C9) values (?,?)', + [42, StringIO('lifecycle test')]) + con.commit() + cur.stream_blobs.append('C9') + cur.execute('select C9 from T2 where C1 = 42') + reader = cur.fetchone()[0] + assert con._lifecycle is cur._lifecycle + assert con._lifecycle is cur._result._lifecycle + assert con._lifecycle is reader._lifecycle + assert con._lifecycle is reader._blob._lifecycle + for interface in (cur._result, reader._blob): + with error_status(335544741): + with pytest.raises(DatabaseError): + interface._check() + assert con._lifecycle.is_dead + con._lifecycle.is_dead = False + with patch.object(reader, 'close') as close, patch.object(reader._blob, 'release') as release: + con._lifecycle.is_dead = True + try: + reader.__del__() + reader._blob.__del__() + close.assert_not_called() + release.assert_not_called() + finally: + con._lifecycle.is_dead = False + + +def test_dead_connection_finalizers_skip_native_cleanup(dsn): + with connect(dsn) as con: + with con.cursor() as cur: + cur.execute('select * from country') + tra = con.main_transaction + stmt = cur._stmt + assert tra._tra._lifecycle is con._lifecycle + assert stmt._istmt._lifecycle is con._lifecycle + assert cur._result._lifecycle is con._lifecycle + with ExitStack() as stack: + targets = [(con, '_close'), (tra, '_finish'), (stmt, 'free'), + (cur, 'close'), (con._att, 'release'), + (tra._tra, 'release'), (stmt._istmt, 'release'), + (cur._result, 'release')] + mocks = [stack.enter_context(patch.object(obj, method)) + for obj, method in targets] + con._lifecycle.is_dead = True + try: + for obj in (con, tra, stmt, cur, con._att, tra._tra, + stmt._istmt, cur._result): + obj.__del__() + for method in mocks: + method.assert_not_called() + finally: + con._lifecycle.is_dead = False + + +def test_distributed_transaction_finalizer_checks_each_connection(dsn): + with connect(dsn) as first, connect(dsn) as second: + dt = DistributedTransactionManager((first, second)) + assert dt._lifecycles == (first._lifecycle, second._lifecycle) + dt._tra = object() + with patch.object(dt, '_finish') as finish: + second._lifecycle.is_dead = True + try: + dt.__del__() + finish.assert_not_called() + finally: + second._lifecycle.is_dead = False + dt._tra = None From 47ccc536843c36c6b6025496aa0ad95b4c1eb2fa Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Fri, 30 Oct 2026 17:28:49 +0100 Subject: [PATCH 46/48] Version for release --- CHANGELOG.md | 2 +- src/firebird/driver/__init__.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0966a24..c830c65 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). -## [2.1.1.dev0] - Unreleased development version +## [2.1.1] - 2026-11-30 ### Fixed diff --git a/src/firebird/driver/__init__.py b/src/firebird/driver/__init__.py index 2da3f14..7f63f7a 100644 --- a/src/firebird/driver/__init__.py +++ b/src/firebird/driver/__init__.py @@ -134,5 +134,5 @@ TIMEOUT, ) -__VERSION__ = '2.1.1.dev0' +__VERSION__ = '2.1.1' "Current driver version, SEMVER string." From cd4c6267b34d55fee70b1d85d2ea043bc13ac8cb Mon Sep 17 00:00:00 2001 From: "F.D.Castel" Date: Sat, 31 Oct 2026 03:05:30 -0300 Subject: [PATCH 47/48] Fix Server text output splitting multi-byte characters across service responses The service fills each text output response by size, not by character, so a response can end inside a multi-byte character. `_query_output()` decoded every response on its own with `read_sized_string()`, which turned both halves of such a character into U+FFFD with errors='replace', and raised UnicodeDecodeError with the default errors='strict'. Decode responses through an incremental decoder that keeps the bytes of an unfinished character until the next response. The decoder is reset with the rest of the output state in `_reset_output()`, and flushed at the end of output (and at the end of each LINE-mode line), so a character that never completes still goes to the error handler instead of being dropped. --- src/firebird/driver/core.py | 15 ++++++++++++++- tests/test_server.py | 38 ++++++++++++++++++++++++++++++++++++- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/src/firebird/driver/core.py b/src/firebird/driver/core.py index 8d848a7..a0f5826 100644 --- a/src/firebird/driver/core.py +++ b/src/firebird/driver/core.py @@ -43,6 +43,7 @@ from __future__ import annotations import atexit +import codecs import contextlib import datetime import decimal @@ -5622,6 +5623,7 @@ def __init__(self, svc: iService, spb: bytes, host: str, encoding: str, "Response buffer used to communicate with service" self._eof: bool = False self.__line_buffer: list[str] = [] + self.__decoder: codecs.IncrementalDecoder | None = None self.encoding: str = encoding "Encoding used for text data exchange with server" self.encoding_errors: str = encoding_errors @@ -5655,6 +5657,7 @@ def _engine_version(self) -> float: def _reset_output(self) -> None: self._eof = False self.__line_buffer.clear() + self.__decoder = None def _make_request(self, timeout: int) -> bytes: if timeout == -1: return None @@ -5686,7 +5689,14 @@ def _query_output(self, timeout: int) -> str | Sentinel: return TIMEOUT if tag != self.mode: # pragma: no cover raise InterfaceError(f"Service responded with error code: {tag}") - return self.response.read_sized_string(encoding=self.encoding, errors=self.encoding_errors) + if self.__decoder is None: + self.__decoder = codecs.getincrementaldecoder(self.encoding)(self.encoding_errors) + # The service fills responses by size, so one can end inside a multi-byte character. + # The incremental decoder keeps those bytes until the next response completes it. + return self.__decoder.decode(self.response.read_bytes()) + def _flush_output(self) -> str: + """Decode bytes left from an unfinished character at the end of output or of a line.""" + return self.__decoder.decode(b'', final=True) def _read_output(self, *, init: str='') -> bool: """Fetch output into the line buffer; return True if the query timed out.""" data = self._query_output(self.query_timeout) @@ -5697,6 +5707,8 @@ def _read_output(self, *, init: str='') -> bool: timed_out = tag == isc_info_svc_timeout if self.mode is SrvInfoCode.TO_EOF: self._eof = tag == isc_info_end + if self._eof: + data += self._flush_output() else: # LINE mode while tag == isc_info_truncated: part = self._query_output(self.query_timeout) @@ -5709,6 +5721,7 @@ def _read_output(self, *, init: str='') -> bool: if not timed_out and tag != isc_info_end: # pragma: no cover raise InterfaceError("Malformed result buffer (missing isc_info_end item)") if not timed_out: + data += self._flush_output() self._eof = not data init += data if data and self.mode is SrvInfoCode.LINE and not timed_out: diff --git a/tests/test_server.py b/tests/test_server.py index 1043c74..11d4ef1 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -192,7 +192,7 @@ def detach(self): def output_response(mode, data='', tag=1): - encoded = data.encode('utf8') + encoded = data if isinstance(data, bytes) else data.encode('utf8') return bytes([mode]) + len(encoded).to_bytes(2, 'little') + encoded + bytes([tag]) @@ -269,6 +269,42 @@ def test_text_output_non_lf_line_boundary_keeps_following_lines(timeout): finally: server.close() +@pytest.mark.parametrize('mode', [SrvInfoCode.LINE, SrvInfoCode.TO_EOF]) +@pytest.mark.parametrize('timeout', [-1, 1]) +@pytest.mark.parametrize('errors', ['strict', 'replace']) +def test_text_output_multibyte_character_split_across_responses(mode, timeout, errors): + # The service fills each response by size, so a response can end inside a multi-byte + # character. The character must survive, also when a timeout falls between the halves. + line = 'a\xe7\xe3o' + encoded = line.encode('utf8') + head, tail = encoded[:2], encoded[2:] # split inside the 2-byte '\xe7' + if mode is SrvInfoCode.TO_EOF: + tail += b'\n' + responses = [output_response(mode, head, 2)] + if timeout > 0: + responses.append(bytes([SrvInfoCode.TIMEOUT])) + responses.extend([output_response(mode, tail), output_response(mode)]) + server = driver.Server(OutputService(responses), b'', 'localhost', 'utf8', errors) + server.mode = mode + server.query_timeout = timeout + try: + assert server.readlines() == [line + '\n'] + finally: + server.close() + +@pytest.mark.parametrize('mode', [SrvInfoCode.LINE, SrvInfoCode.TO_EOF]) +def test_text_output_incomplete_character_at_end_uses_error_handler(mode): + # A character still incomplete when the output (or a LINE-mode line) ends is not + # silently dropped; the error handler decides, as for any other invalid input. + responses = [output_response(mode, b'ab\xc3'), output_response(mode)] + server = driver.Server(OutputService(responses), b'', 'localhost', 'utf8', 'replace') + server.mode = mode + try: + expected = 'ab' + chr(0xFFFD) + assert server.readlines() == [expected + '\n' if mode is SrvInfoCode.LINE else expected] + finally: + server.close() + def test_get_limbo_transaction_ids(server_connection, db_file): pytest.skip('Not implemented yet') ids = server_connection.database.get_limbo_transaction_ids(database=str(db_file)) From b35613181255c17922ba3fb59c83ff148ac84108 Mon Sep 17 00:00:00 2001 From: Pavel Cisar Date: Sat, 31 Oct 2026 10:03:54 +0100 Subject: [PATCH 48/48] Prepare 2.1.2 release --- CHANGELOG.md | 9 ++++++++- src/firebird/driver/__init__.py | 2 +- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c830c65..24526c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,14 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). -## [2.1.1] - 2026-11-30 +## [2.1.2] - 2026-10-31 + +### Fixed + +- GH-80: Preserve multibyte characters split across service text output responses, including + when a timeout occurs between responses. + +## [2.1.1] - 2026-10-30 ### Fixed diff --git a/src/firebird/driver/__init__.py b/src/firebird/driver/__init__.py index 7f63f7a..845c3e4 100644 --- a/src/firebird/driver/__init__.py +++ b/src/firebird/driver/__init__.py @@ -134,5 +134,5 @@ TIMEOUT, ) -__VERSION__ = '2.1.1' +__VERSION__ = '2.1.2' "Current driver version, SEMVER string."