Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion beanquery/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,23 @@ 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:
# Dotted schemes can fail on a missing parent source package.
# Propagate import failures for other modules.
missing = exc.name
missing_source = (
missing == source_name or
(missing is not None and missing.startswith('beanquery.sources.') and
source_name.startswith(f'{missing}.'))
)
Comment on lines +58 to +62

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you explain what this code is doing? I cannot understand why it is needed in the form it is written.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Python can name a missing parent package instead of the requested module. For foo.bar:ledger, the import requests beanquery.sources.foo.bar, but exc.name can be beanquery.sources.foo.

The predicate converts a missing source module or one of its parents below beanquery.sources to OperationalError. It re-raises unrelated dependency errors, and excludes beanquery.sources itself. source.attach() runs outside the handler so its failures also propagate.

I've named exc.name locally and added a comment explaining the dotted-parent case. The real dotted-scheme and dependency tests pass, along with all 303 Linux tests, Ruff, ten Windows connection tests and both package builds.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems still very much LLM crap. I warned you. Goodbye

if not missing_source:
raise
raise OperationalError(f'unknown source scheme: {scheme!r}') from None
source.attach(self, dsn, **kwargs)

def close(self):
Expand Down
72 changes: 72 additions & 0 deletions beanquery/connection_test.py
Original file line number Diff line number Diff line change
@@ -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,)])
4 changes: 2 additions & 2 deletions beanquery/query_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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:
Expand Down
6 changes: 3 additions & 3 deletions beanquery/shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down