From 9f642c8cc4e485471a8d5b3bf2139d48f2257645 Mon Sep 17 00:00:00 2001 From: Ryan Duguid Date: Fri, 2 Oct 2026 10:33:58 +1000 Subject: [PATCH 1/4] fix: report missing and unknown source schemes as OperationalError --- beanquery/__init__.py | 15 +++++++- beanquery/connection_test.py | 72 ++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 beanquery/connection_test.py diff --git a/beanquery/__init__.py b/beanquery/__init__.py index e997631f..59059def 100644 --- a/beanquery/__init__.py +++ b/beanquery/__init__.py @@ -46,7 +46,20 @@ def __init__(self, dsn='', **kwargs): def attach(self, dsn, **kwargs): scheme = urlparse(dsn).scheme - source = importlib.import_module(f'beanquery.sources.{scheme}') + if not scheme: + raise OperationalError('missing source scheme') + source_name = f'beanquery.sources.{scheme}' + try: + source = importlib.import_module(source_name) + except ModuleNotFoundError as exc: + missing_source = ( + exc.name == source_name or + (exc.name is not None and exc.name.startswith('beanquery.sources.') and + source_name.startswith(f'{exc.name}.')) + ) + if not missing_source: + raise + raise OperationalError(f'unknown source scheme: {scheme!r}') from None source.attach(self, dsn, **kwargs) def close(self): diff --git a/beanquery/connection_test.py b/beanquery/connection_test.py new file mode 100644 index 00000000..ab2e766a --- /dev/null +++ b/beanquery/connection_test.py @@ -0,0 +1,72 @@ +import unittest +from unittest import mock + +import beanquery + + +class TestConnection(unittest.TestCase): + def test_connect_without_source(self): + for dsn in [None, '']: + with self.subTest(dsn=dsn): + connection = beanquery.connect(dsn) + self.assertEqual(connection.execute('SELECT 42').fetchall(), [(42,)]) + + def test_missing_scheme(self): + connection = beanquery.connect(None) + for dsn in ['', 'ledger.beancount', './ledger.beancount']: + with self.subTest(dsn=dsn), self.assertRaisesRegex(beanquery.OperationalError, '^missing source scheme$'): + connection.attach(dsn) + + def test_connect_missing_scheme(self): + with self.assertRaisesRegex(beanquery.OperationalError, '^missing source scheme$'): + beanquery.connect('ledger.beancount') + + def test_unknown_scheme(self): + for scheme in ['beancounnt', 'unknown', 'foo.bar', 'foo.bar.baz', 'foo+bar', 'foo-bar']: + with self.subTest(scheme=scheme): + with self.assertRaises(beanquery.OperationalError) as caught: + beanquery.connect(f'{scheme}:ledger') + self.assertEqual(str(caught.exception), f'unknown source scheme: {scheme!r}') + + def test_message_only_contains_scheme(self): + with self.assertRaises(beanquery.OperationalError) as caught: + beanquery.connect('unknown://example.invalid/private-ledger?fixture=synthetic') + self.assertEqual(str(caught.exception), "unknown source scheme: 'unknown'") + + def test_import_dependency_failure(self): + names = ['some_dependency', 'beanquery.sources', 'beanquery.sources.other', 'beanquery.sources.foo.optional', None] + for name in names: + error = ModuleNotFoundError('missing dependency', name=name) + with self.subTest(name=name), mock.patch('beanquery.importlib.import_module', side_effect=error): + with self.assertRaises(ModuleNotFoundError) as caught: + beanquery.connect('foo.bar:ledger') + self.assertIs(caught.exception, error) + + def test_import_error(self): + error = ImportError('source import failed') + with mock.patch('beanquery.importlib.import_module', side_effect=error): + with self.assertRaises(ImportError) as caught: + beanquery.connect('test:') + self.assertIs(caught.exception, error) + + def test_source_attach_failure(self): + error = ModuleNotFoundError('source attach failed', name='beanquery.sources.test') + source = mock.Mock() + source.attach.side_effect = error + with mock.patch('beanquery.importlib.import_module', return_value=source): + with self.assertRaises(ModuleNotFoundError) as caught: + beanquery.connect('test:') + self.assertIs(caught.exception, error) + + def test_source_attach_arguments(self): + source = mock.Mock() + dsn = 'test:fixture?name=example' + entries = [] + options = {'example': 'synthetic'} + with mock.patch('beanquery.importlib.import_module', return_value=source): + connection = beanquery.connect(dsn, entries=entries, options=options) + source.attach.assert_called_once_with(connection, dsn, entries=entries, options=options) + + def test_valid_source(self): + connection = beanquery.connect('test:magic?name=example&start=1&stop=3') + self.assertEqual(connection.execute('SELECT x FROM #example').fetchall(), [(1,), (2,)]) From 3c760fec0ae71bfac8bc29a25882e22f7ff17a60 Mon Sep 17 00:00:00 2001 From: Ryan Duguid Date: Fri, 2 Oct 2026 13:19:08 +1000 Subject: [PATCH 2/4] ci: preserve established renderer and command signatures under Ruff 0.16 --- pyproject.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index 2ff7aac0..edf4a2a0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -94,3 +94,6 @@ exclude = [ [tool.ruff.lint.per-file-ignores] 'beanquery/query_env.py' = ['F811'] +# Preserve the established renderer and command signatures. +'beanquery/query_render.py' = ['PLR0917'] +'beanquery/shell.py' = ['PLR0917'] From 7f604793d16ac23d59154f75c0ae24c9f383b5af Mon Sep 17 00:00:00 2001 From: Ryan Duguid Date: Fri, 2 Oct 2026 13:42:58 +1000 Subject: [PATCH 3/4] ci: scope Ruff positional-argument exceptions to existing functions --- beanquery/query_render.py | 4 ++-- beanquery/shell.py | 6 +++--- pyproject.toml | 3 --- 3 files changed, 5 insertions(+), 8 deletions(-) diff --git a/beanquery/query_render.py b/beanquery/query_render.py index 24d53618..107bedf4 100644 --- a/beanquery/query_render.py +++ b/beanquery/query_render.py @@ -486,7 +486,7 @@ def _get_renderer(datatype, ctx): return renderer(ctx) -def render_text(columns, rows, dcontext, file, expand=False, boxed=False, +def render_text(columns, rows, dcontext, file, expand=False, boxed=False, # noqa: PLR0917 spaced=False, listsep=' ', nullvalue='', narrow=True, unicode=False, **kwargs): """Render the result of executing a query in text format. @@ -552,7 +552,7 @@ def render_text(columns, rows, dcontext, file, expand=False, boxed=False, file.write(bottom) -def render_csv(columns, rows, dcontext, file, expand=False, nullvalue='', **kwargs): +def render_csv(columns, rows, dcontext, file, expand=False, nullvalue='', **kwargs): # noqa: PLR0917 """Render the result of executing a query in text format. Args: diff --git a/beanquery/shell.py b/beanquery/shell.py index c28ab3b2..3f96f74e 100644 --- a/beanquery/shell.py +++ b/beanquery/shell.py @@ -53,7 +53,7 @@ def strip(cls, x): return cls.ESCAPES.sub('', x) -def render_location(text, pos, endpos, lineno, indent, strip, out): +def render_location(text, pos, endpos, lineno, indent, strip, out): # noqa: PLR0917 length = endpos - pos lines = text.splitlines(True) for line in lines[:lineno]: @@ -374,7 +374,7 @@ class BQLShell(DispatchingShell): """An interactive shell interpreter for the Beancount query language.""" prompt = 'beanquery> ' - def __init__(self, source, outfile, interactive=False, runinit=False, format='text', numberify=False, errors=True): + def __init__(self, source, outfile, interactive=False, runinit=False, format='text', numberify=False, errors=True): # noqa: PLR0917 settings = Settings(format=format, numberify=numberify) super().__init__(outfile, interactive, runinit, settings) self.context = beanquery.connect(None) @@ -779,7 +779,7 @@ def print_statistics(entries, options, errors, outfile): @click.option('--no-errors', '-q', is_flag=True, help="Do not report ledger validation errors on load.") @click.version_option('', message=f'beanquery {beanquery.__version__}, beancount {beancount.__version__}') -def main(filename, query, numberify, format, output, no_errors): +def main(filename, query, numberify, format, output, no_errors): # noqa: PLR0917 """An interactive interpreter for the Beancount Query Language. Load Beancount ledger FILENAME and run Beancount Query Language diff --git a/pyproject.toml b/pyproject.toml index edf4a2a0..2ff7aac0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -94,6 +94,3 @@ exclude = [ [tool.ruff.lint.per-file-ignores] 'beanquery/query_env.py' = ['F811'] -# Preserve the established renderer and command signatures. -'beanquery/query_render.py' = ['PLR0917'] -'beanquery/shell.py' = ['PLR0917'] From 36f2dffe52d6954433a2f0a4f4613a8087e599fd Mon Sep 17 00:00:00 2001 From: Ryan Duguid Date: Fri, 2 Oct 2026 22:57:00 +1000 Subject: [PATCH 4/4] docs: explain dotted source import errors --- beanquery/__init__.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/beanquery/__init__.py b/beanquery/__init__.py index 59059def..d6789544 100644 --- a/beanquery/__init__.py +++ b/beanquery/__init__.py @@ -52,10 +52,13 @@ def attach(self, dsn, **kwargs): try: source = importlib.import_module(source_name) except ModuleNotFoundError as exc: + # Dotted schemes can fail on a missing parent source package. + # Propagate import failures for other modules. + missing = exc.name missing_source = ( - exc.name == source_name or - (exc.name is not None and exc.name.startswith('beanquery.sources.') and - source_name.startswith(f'{exc.name}.')) + missing == source_name or + (missing is not None and missing.startswith('beanquery.sources.') and + source_name.startswith(f'{missing}.')) ) if not missing_source: raise