Conghao97's picture tcftrees's picture
ProgramGen release
d086025
|
Raw History Blame Contribute Delete
98.7 kB

adobe/dy-sql

Project Overview

Dynamic SQL (dy-sql) is a Python library that eases integration with SQL databases through a small set of declarative decorators. Its purpose is to remove boilerplate from database access: instead of hand-writing connection, pool, and cursor management, developers annotate ordinary Python functions with @sqlquery, @sqlupdate, or @sqlexists, supply a QueryData object carrying a parameterized SQL statement along with optional query_params and template_params, and receive mapped results back. The package is scoped to relational databases, with first-class support for MariaDB/MySQL-style backends, and focuses on query execution and result mapping rather than schema management or ORM-style entity tracking.

Primary functionality includes select queries with pluggable result mappers (RecordCombiningMapper, SingleRowMapper, SingleColumnMapper, SingleRowAndColumnMapper, CountMapper, and KeyValueMapper, plus custom mappers derived from BaseMapper), data-changing operations that can yield multiple QueryData objects executed inside a single transaction with support for last-insert-id callbacks, and an existence check decorator that wraps queries into SELECT EXISTS form. Template helpers such as in, not_in, in_multi_column, and values generators simplify building IN clauses and bulk inserts safely.

Architecturally, the dysql package is organized into modules for connection pooling and database initialization (connections, databases), query parsing and templates (query_utils), record mapping (mappers and pydantic_mappers, which offer DbMapResult and pydantic-based DbMapResultModel with annotations like FromCSVToList), multitenancy support (multitenancy, set_current_database, tenant_database_manager, use_database_tenant), error handling, and testing utilities (test_managers such as MariaDbTestManager). Configuration entry points like set_default_connection_parameters and set_database_init_hook initialize connection pools and instrument engines, making the library suitable for minimal-setup, decorator-driven data access layers in production services.

Re-implement this repository from scratch so that the original test suite passes. The sections below document the language/environment, the project structure, the public API the tests exercise, and per-capability implementation guidance.

Submission Constraints (read carefully — the evaluation depends on these)

This is a closed-book task. The graded test suite is hidden and will be injected into the workspace at evaluation time. To be scored correctly you MUST follow these rules:

  1. Do NOT create or modify any files under the test directories (e.g. tests/, test/, testing/, or files named test_*.py / conftest.py). The grader injects its own test files at those paths; any file you place there will collide with the injected suite and cause the whole evaluation to score 0. Implement only the library/source code — never the tests.

  2. Your package MUST be importable by the name the tests use. The hidden tests import your package by its documented top-level name (see the Project Directory Structure and API Usage Guide below). Provide a valid pyproject.toml / setup.py / setup.cfg and lay out your modules so that pip install -e . succeeds and the package imports cleanly. If your package is not installable/importable, every test errors out and the reward is 0.

  3. Match the documented module paths and public API exactly (names, signatures, and any literal error/exception strings). Internal helpers not listed in the API guide may be implemented however you like.

Install / Reconstruction Contract

Follow this contract before implementing the documented APIs:

  • Project root: /workspace/repo at runtime; the submitted repository root is ..
  • Package/distribution name: dy-sql
  • Package roots: .
  • Install strategy: editable-install
  • Import/entry: use the package and public entry points listed in the API Usage Guide; do not invent a different top-level package.
  • Provision commands:
    python3 -I -c 'import base64; from pathlib import Path; Path('"'"'/tmp/programgen-pip-compat-v1.py'"'"').write_bytes(base64.b64decode('"'"'aW1wb3J0IG9zCmZyb20gcGF0aGxpYiBpbXBvcnQgUGF0aAppbXBvcnQgc3VicHJvY2VzcwppbXBvcnQgc3lzCmltcG9ydCB0ZW1wZmlsZQoKZGVmIGNvbnN0cmFpbmVkX2J1aWxkX2luc3RhbGwoY29tbWFuZCwgcnVuKToKICAgIGNvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCgnUFJPR1JBTUdFTl9CVUlMRF9DT05TVFJBSU5UJykKICAgIGlmIG5vdCBjb25zdHJhaW50IG9yICctLW5vLWJ1aWxkLWlzb2xhdGlvbicgaW4gY29tbWFuZDoKICAgICAgICByZXR1cm4gTm9uZQogICAgaWYgc3lzLnZlcnNpb25faW5mb1s6Ml0gPCAoMywgOSk6CiAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSBpc29sYXRlZCBidWlsZCBjb25zdHJhaW50cyByZXF1aXJlIFB5dGhvbiA+PTMuOScsIGZsdXNoPVRydWUpCiAgICAgICAgcmV0dXJuIDEKICAgICMgQSBkZWRpY2F0ZWQgaW5zdGFsbGVyIGNvbnRyb2xzIFBFUCA1MTcgYnVpbGQgZGVwZW5kZW5jaWVzIG9ubHkuIEl0IGRvZXMKICAgICMgbm90IHVwZ3JhZGUgcGlwL3NldHVwdG9vbHMgaW4gdGhlIG1lYXN1cmVkIHByb2plY3QncyBydW50aW1lIGVudmlyb25tZW50LgogICAgd2l0aCB0ZW1wZmlsZS5UZW1wb3JhcnlEaXJlY3RvcnkocHJlZml4PSdwcm9ncmFtZ2VuLWJ1aWxkLWluc3RhbGxlci0nKSBhcyBkaXJlY3Rvcnk6CiAgICAgICAgcnVubmVyID0gc3RyKFBhdGgoZGlyZWN0b3J5KSAvICdiaW4nIC8gJ3B5dGhvbicpCiAgICAgICAgZm9yIHNldHVwIGluIChbc3lzLmV4ZWN1dGFibGUsICctbScsICd2ZW52JywgZGlyZWN0b3J5XSwKICAgICAgICAgICAgICAgICAgICAgIFtydW5uZXIsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICctLW5vLWNhY2hlLWRpcicsICdwaXA9PTI1LjMnXSk6CiAgICAgICAgICAgIHJlc3VsdCA9IHJ1bihzZXR1cCkKICAgICAgICAgICAgaWYgcmVzdWx0LnJldHVybmNvZGU6CiAgICAgICAgICAgICAgICByZXR1cm4gcmVzdWx0LnJldHVybmNvZGUKICAgICAgICBpZiBjb21tYW5kWzo0XSAhPSBbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCddIGFuZCBjb21tYW5kWzo0XSAhPSBbJ3B5dGhvbjMnLCAnLW0nLCAncGlwJywgJ2luc3RhbGwnXToKICAgICAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSB1bnN1cHBvcnRlZCBjb25zdHJhaW5lZCBpbnN0YWxsZXIgY29tbWFuZCcsIGZsdXNoPVRydWUpCiAgICAgICAgICAgIHJldHVybiAxCiAgICAgICAgdGFyZ2V0ID0gW3J1bm5lciwgJy1tJywgJ3BpcCcsICctLXB5dGhvbicsIHN5cy5leGVjdXRhYmxlLCAnaW5zdGFsbCcsCiAgICAgICAgICAgICAgICAgICctLWJ1aWxkLWNvbnN0cmFpbnQnLCBjb25zdHJhaW50XSArIGNvbW1hbmRbNDpdCiAgICAgICAgcmV0dXJuIHJ1bih0YXJnZXQpLnJldHVybmNvZGUKCmRlZiBpbnN0YWxsKGNvbW1hbmQsIHJ1bj1zdWJwcm9jZXNzLnJ1bik6CiAgICBmb3IgdmFyaWFibGUgaW4gKCdQUk9HUkFNR0VOX1JVTlRJTUVfQ09OU1RSQUlOVCcsICdQUk9HUkFNR0VOX1JVTlRJTUVfUkVQQUlSX0NPTlNUUkFJTlQnKToKICAgICAgICBydW50aW1lX2NvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCh2YXJpYWJsZSkKICAgICAgICBpZiBydW50aW1lX2NvbnN0cmFpbnQ6CiAgICAgICAgICAgIGNvbW1hbmQgPSBsaXN0KGNvbW1hbmQpICsgWyctYycsIHJ1bnRpbWVfY29uc3RyYWludF0KICAgIGNvbnN0cmFpbmVkID0gY29uc3RyYWluZWRfYnVpbGRfaW5zdGFsbChjb21tYW5kLCBydW4pCiAgICBpZiBjb25zdHJhaW5lZCBpcyBub3QgTm9uZToKICAgICAgICByZXR1cm4gY29uc3RyYWluZWQKICAgIHJlc3VsdCA9IHJ1bihjb21tYW5kLCBzdGRvdXQ9c3VicHJvY2Vzcy5QSVBFLCBzdGRlcnI9c3VicHJvY2Vzcy5TVERPVVQsIHRleHQ9VHJ1ZSkKICAgIG91dHB1dCA9IHJlc3VsdC5zdGRvdXQgb3IgJycKICAgIHN5cy5zdGRvdXQud3JpdGUob3V0cHV0KQogICAgc3lzLnN0ZG91dC5mbHVzaCgpCiAgICBpZiByZXN1bHQucmV0dXJuY29kZSA9PSAwOgogICAgICAgIHJldHVybiAwCiAgICBsZWdhY3kgPSAnaW52YWxpZCBtZXRhZGF0YScgaW4gb3V0cHV0Lmxvd2VyKCkgYW5kICdwbGVhc2UgdXNlIHBpcDwyNC4xJyBpbiBvdXRwdXQubG93ZXIoKQogICAgaWYgbm90IGxlZ2FjeSBvciBub3QgKDMsIDgpIDw9IHN5cy52ZXJzaW9uX2luZm9bOjJdIDw9ICgzLCAxMik6CiAgICAgICAgcmV0dXJuIHJlc3VsdC5yZXR1cm5jb2RlCiAgICBwcmludCgnW3Byb2dyYW1nZW5dIGxlZ2FjeSBkaXN0cmlidXRpb24gbWV0YWRhdGE6IHJldHJ5aW5nIHRoZSB1bmNoYW5nZWQgcmVxdWlyZW1lbnRzIHdpdGggcGlwPDI0LjEnLCBmbHVzaD1UcnVlKQogICAgY2hhbmdlZCA9IHJ1bihbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICdwaXA8MjQuMSddKQogICAgaWYgY2hhbmdlZC5yZXR1cm5jb2RlOgogICAgICAgIHJldHVybiBjaGFuZ2VkLnJldHVybmNvZGUKICAgIHJldHVybiBydW4oY29tbWFuZCkucmV0dXJuY29kZQoKaWYgX19uYW1lX18gPT0gJ19fbWFpbl9fJzoKICAgIHJhaXNlIFN5c3RlbUV4aXQoaW5zdGFsbChzeXMuYXJndlsxOl0pKQo='"'"'))'
    programgen_pip_install() { python3 -I /tmp/programgen-pip-compat-v1.py "$@"; }
    export -f programgen_pip_install
    programgen_pip_install python3 -m pip install -U pip 'setuptools<82' wheel
    programgen_pip_install python3 -m pip install uv_build
    (
    programgen_install_report="$(mktemp)"
    trap 'rm -f "$programgen_install_report"' EXIT
    SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 programgen_pip_install python3 -m pip install -e . --no-build-isolation --no-deps --report "$programgen_install_report"
    python3 -c 'exec("import json,subprocess,sys\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.utils import canonicalize_name\nreport=json.load(open(sys.argv[1], encoding='"'"'utf-8'"'"'))\n\nrequested={canonicalize_name(name) for name in ()}\nrequirements=[]\nfor item in report.get('"'"'install'"'"', []):\n    metadata=item.get('"'"'metadata'"'"', {})\n    name=canonicalize_name(metadata.get('"'"'name'"'"', '"'"''"'"'))\n    provided={canonicalize_name(value) for value in metadata.get('"'"'provides_extra'"'"', [])}\n    selected={'"'"''"'"'} | (provided & requested)\n    parsed=[Requirement(value) for value in metadata.get('"'"'requires_dist'"'"', [])]\n    while True:\n        added=set()\n        for requirement in parsed:\n            if requirement.marker is not None and not any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n                continue\n            if canonicalize_name(requirement.name)==name:\n                if requirement.url or (requirement.specifier and not requirement.specifier.contains(metadata.get('"'"'version'"'"', '"'"''"'"'), prereleases=True)):\n                    raise ValueError('"'"'local extra requires a different target distribution'"'"')\n                extras={canonicalize_name(value) for value in requirement.extras}\n                if not extras <= provided:\n                    raise ValueError('"'"'local extra refers to an undeclared extra'"'"')\n                added.update(extras - selected)\n        if not added:\n            break\n        selected.update(added)\n    for requirement in parsed:\n        if canonicalize_name(requirement.name)==name:\n            continue\n        if requirement.marker is None or any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n            requirement.marker=None\n            requirements.append(str(requirement))\nrequirements=list(dict.fromkeys(requirements))\nsubprocess.run([sys.executable, '"'"'-I'"'"', '"'"'/tmp/programgen-pip-compat-v1.py'"'"', sys.executable, '"'"'-m'"'"', '"'"'pip'"'"', '"'"'install'"'"', *requirements], check=True) if requirements else None\n")' "$programgen_install_report"
    )
    
  • Runtime setup:
    {
      [ -e "$PWD"/README.rst ] || { mkdir -p "$(dirname "$PWD"/README.rst)"; : > "$PWD"/README.rst; };
      SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 SETUPTOOLS_SCM_WRITE_TO_SOURCE=1 python3 -m pip install -e "$PWD" --no-build-isolation --no-deps;
    }
    
  • Project root for installation: .
  • Build-version environment: SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0, PDM_BUILD_SCM_VERSION=0.0.0, POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0, UV_DYNAMIC_VERSIONING_BYPASS=0.0.0
  • Test directory: dysql, dysql/test
  • Test command: bash -lc 'set -uo pipefail run=(python3 -m pytest -vv -o addopts= dysql/test/test_annotations.py dysql/test/test_database_initialization.py dysql/test/test_mappers.py dysql/test/test_mariadbmap_tojson.py dysql/test/test_pydantic_mappers.py dysql/test/test_sql_decorator.py dysql/test/test_sql_exists_decorator.py dysql/test/test_sql_in_list_templates.py dysql/test/test_sql_insert_templates.py dysql/test/test_template_generators.py dysql/test/test_test_managers.py dysql/test_managers.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= dysql/test/test_annotations.py dysql/test/test_database_initialization.py dysql/test/test_mappers.py dysql/test/test_mariadbmap_tojson.py dysql/test/test_pydantic_mappers.py dysql/test/test_sql_decorator.py dysql/test/test_sql_exists_decorator.py dysql/test/test_sql_in_list_templates.py dysql/test/test_sql_insert_templates.py dysql/test/test_template_generators.py dysql/test/test_test_managers.py dysql/test_managers.py); fi collect=(python3 -m pytest -q -o addopts= dysql/test/test_annotations.py dysql/test/test_database_initialization.py dysql/test/test_mappers.py dysql/test/test_mariadbmap_tojson.py dysql/test/test_pydantic_mappers.py dysql/test/test_sql_decorator.py dysql/test/test_sql_exists_decorator.py dysql/test/test_sql_in_list_templates.py dysql/test/test_sql_insert_templates.py dysql/test/test_template_generators.py dysql/test/test_test_managers.py dysql/test_managers.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '"'"'/::/p'"'"' | sed '"'"'s/[[:space:]]*$//'"'"') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'"'"'::'"'"' -v limit=500 '"'"'{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}'"'"') fi "${run[@]}"; exit $?'
  • Test startup: run the exact test command above from the project root after installation; hidden tests are injected separately.

Environment & Project Structure

  • Language: python
  • Build system: python
  • Test command: bash -lc set -uo pipefail run=(python3 -m pytest -vv -o addopts= dysql/test/test_annotations.py dysql/test/test_database_initialization.py dysql/test/test_mappers.py dysql/test/test_mariadbmap_tojson.py dysql/test/test_pydantic_mappers.py dysql/test/test_sql_decorator.py dysql/test/test_sql_exists_decorator.py dysql/test/test_sql_in_list_templates.py dysql/test/test_sql_insert_templates.py dysql/test/test_template_generators.py dysql/test/test_test_managers.py dysql/test_managers.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= dysql/test/test_annotations.py dysql/test/test_database_initialization.py dysql/test/test_mappers.py dysql/test/test_mariadbmap_tojson.py dysql/test/test_pydantic_mappers.py dysql/test/test_sql_decorator.py dysql/test/test_sql_exists_decorator.py dysql/test/test_sql_in_list_templates.py dysql/test/test_sql_insert_templates.py dysql/test/test_template_generators.py dysql/test/test_test_managers.py dysql/test_managers.py); fi collect=(python3 -m pytest -q -o addopts= dysql/test/test_annotations.py dysql/test/test_database_initialization.py dysql/test/test_mappers.py dysql/test/test_mariadbmap_tojson.py dysql/test/test_pydantic_mappers.py dysql/test/test_sql_decorator.py dysql/test/test_sql_exists_decorator.py dysql/test/test_sql_in_list_templates.py dysql/test/test_sql_insert_templates.py dysql/test/test_template_generators.py dysql/test/test_test_managers.py dysql/test_managers.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '/::/p' | sed 's/[[:space:]]*$//') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'::' -v limit=500 '{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}') fi "${run[@]}"; exit $?

Project Directory Structure

.github/CONTRIBUTING.md
.github/ISSUE_TEMPLATE.md
.github/PULL_REQUEST_TEMPLATE.md
.github/workflows/build.yaml
.gitignore
.pre-commit-config.yaml
.python-version
BASE_VERSION
CODE_OF_CONDUCT.md
Dockerfile
LICENSE
README.rst
dysql/__init__.py
dysql/annotations.py
dysql/connections.py
dysql/databases.py
dysql/exceptions.py
dysql/mappers.py
dysql/multitenancy.py
dysql/pydantic_mappers.py
dysql/query_utils.py
dysql/test_managers.py
pyproject.toml
uv.lock

API Usage Guide

Each capability below lists the components the tests exercise with their exact signatures and behavior. Re-create these so the tests pass; internal helpers not listed here may be implemented freely.

Capability: Database connection parameter setup and engine initialization

Purpose

This capability is the library's boot sequence. set_default_connection_parameters captures MySQL/MariaDB connection settings before any SQL runs; nothing connects at configuration time. The registered values are defaults: QueryData supplied by a decorated query may override them at execution time (the docstring says they "may be overridden by parameters provided in the QueryData, hence the 'default'"). The first decorated query (@sqlquery, @sqlupdate, @sqlexists) that needs a connection walks DatabaseContainerSingleton → DatabaseContainer.current_database → Database.engine, and only then is a pooled SQLAlchemy Engine built and cached.

Realistic workflow

  1. Optionally register set_database_init_hook(hook) first. The hook is stored as a class attribute on Database, shared by every database key; it fires once per engine, at build time, so it must be set before the first engine is constructed to have any effect.
  2. Call set_default_connection_parameters. The four required values (host, user, password, database) are falsy-checked; a failure raises DBNotPreparedError immediately, before any state is stored. On success the whole parameter set is merged into _DEFAULT_CONNECTION_PARAMS_BY_KEY[database_key] (database_key defaults to the database name when falsy).
  3. Execute a decorated function. The container resolves the current key — the set_current_database contextvar value when non-empty, otherwise the first key inserted into _DEFAULT_CONNECTION_PARAMS_BY_KEY — and returns the Database for that key, creating and caching it on first request.
  4. Database.engine (first access only) reads the stored params, builds mysql+mysqlconnector://user:password@host:port/database?charset=charset[&collation=collation] via sqlalchemy.create_engine(..., pool_size=..., pool_recycle=..., echo=echo_queries, pool_pre_ping=True), then invokes the hook as hook(database_name, engine) — the stored database name, not the key (they coincide for single-tenant setups).
  5. Engine construction opens no connection: create_engine only constructs the pool and pool_pre_ping pings at checkout, so misconfigured hosts/credentials do not fail at build time — engine-build failures are limited to missing/unknown parameter keys, and the first actual connection (and any connection error) happens when the query executes. This is what lets tests build engines and trigger the hook without a live MySQL server.

State changes

  • _DEFAULT_CONNECTION_PARAMS_BY_KEY is a defaultdict(dict); re-calling with the same key merges (dict.update over the full locals() snapshot, which includes the resolved database_key). Because locals() always contains every parameter, re-registering a key overwrites all of it: optional arguments omitted on the re-call revert to their declared defaults (port=3306, pool_size=10, pool_recycle=3600, echo_queries=False, charset="utf8", collation=None) rather than retaining previously stored values — e.g. a first call with echo_queries=True followed by a re-call that omits echo_queries stores echo_queries=False. Only explicitly passed arguments can differ between calls, and the four required values are re-validated on every call. Different keys register additional (tenant) databases.
  • DatabaseContainer (a dict subclass) caches one Database per key on __getitem__; DatabaseContainerSingleton.__new__ returns the same instance for every construction, and dysql.connections instantiates it at import time.
  • Each Database caches _engine after first build; the hook is not re-fired and later parameter changes are not picked up by an existing engine.

Defaults

port=3306, pool_size=10, pool_recycle=3600, echo_queries=False, charset="utf8", collation=None (omitted from the URL when unset). pool_pre_ping=True is always applied. The driver is mysql-connector-python.

Errors and exact messages

  • Set-time validation: Database parameter "{name}" is not set or empty and is required (name ∈ host/user/password/database; empty string and None both fail).
  • Container guard, raised when __getitem__ runs while the params dict is still empty: Unable to connect to a database, set_default_connection_parameters must first be called.
  • Key miss at engine build: No connection parameters found for database key '{key}' — occurs when set_current_database names a key never configured, or after the params dict is cleared while a Database object exists but has not yet built its engine.

Non-obvious, test-sensitive behavior

  • The engine lookup uses .get(key, {}), so an unknown key does not create an empty entry in the defaultdict.
  • The "must first be called" guard checks _DEFAULT_CONNECTION_PARAMS_BY_KEY, not the container contents; clearing the dict between tests re-arms the guard, while Database objects already cached in the container survive and built engines keep working.
  • set_current_database's key selection is context-local: the key lives in a module-level ContextVar (default ""), so it is scoped to the current async context and inherited by context copies, and does not leak across tasks/coroutines; contexts that never set it fall back to the first-registered key (insertion order), so the first configured database is the implicit default. reset_current_database() is set_current_database("") and only resets the calling context.
  • is_set_current_database_supported() is deprecated and always returns True.
  • Only the four required values are validated; e.g. pool_size=0 passes straight through to create_engine.
  • The hook applies to all keys built after registration, and engines echo queries only when echo_queries=True was stored for that key.

Exact API Reference

dysql.databases.set_database_init_hook

  • Import Path: from dysql.databases import set_database_init_hook
  • Required Test Import Paths:
    • dysql.set_database_init_hook
  • Exact Test Import Statements:
    • from dysql import ( sqlquery, DBNotPreparedError, set_default_connection_parameters, QueryData, set_database_init_hook, )
  • Signature:
def set_database_init_hook(hook_method: Callable[[Optional[str], sqlalchemy.engine.Engine], None]) -> None
  • Behavior: Sets an initialization hook whenever a new database is initialized. This method will receive the database name

dysql.databases.set_default_connection_parameters

  • Import Path: from dysql.databases import set_default_connection_parameters
  • Required Test Import Paths:
    • dysql.databases.set_default_connection_parameters
    • dysql.set_default_connection_parameters
  • Exact Test Import Statements:
    • from .databases import ( is_set_current_database_supported, set_current_database, set_default_connection_parameters, )
    • from dysql import ( sqlquery, DBNotPreparedError, set_default_connection_parameters, QueryData, set_database_init_hook, )
    • from dysql import set_default_connection_parameters, databases
  • Signature:
def set_default_connection_parameters(host: str, user: str, password: str, database: str, database_key: Optional[str]=None, port: int=3306, pool_size: int=10, pool_recycle: int=3600, echo_queries: bool=False, charset: str='utf8', collation: Optional[str]=None)
  • Behavior: Initializes the parameters to use when connecting to the database. This is a subset of the parameters

dysql.databases.DatabaseContainer

  • Import Path: from dysql.databases import DatabaseContainer
  • Signature:
class DatabaseContainer:
    def current_database(self) -> Database
  • Raises (implementation must reproduce these exact messages):
    • Unable to connect to a database, set_default_connection_parameters must first be called
  • Behavior: Implementation of a dictionary that always provides a Database class instance, even if the key is missing.

dysql.mappers.SingleColumnMapper

  • Import Path: from dysql.mappers import SingleColumnMapper
  • Required Test Import Paths:
    • dysql.SingleColumnMapper
  • Exact Test Import Statements:
    • from dysql import ( RecordCombiningMapper, SingleRowMapper, SingleColumnMapper, SingleRowAndColumnMapper, CountMapper, KeyValueMapper, )
  • Kind: class
  • Signature:
class SingleColumnMapper(BaseMapper):
    def map_records(self, records: sqlalchemy.engine.CursorResult) -> Any
  • Behavior: Returns the first column value for each record from the database, even if multiple columns are

dysql.mappers.SingleRowAndColumnMapper

  • Import Path: from dysql.mappers import SingleRowAndColumnMapper
  • Required Test Import Paths:
    • dysql.SingleRowAndColumnMapper
  • Exact Test Import Statements:
    • from dysql import ( RecordCombiningMapper, SingleRowMapper, SingleColumnMapper, SingleRowAndColumnMapper, CountMapper, KeyValueMapper, )
  • Kind: class
  • Signature:
class SingleRowAndColumnMapper(BaseMapper):
    def map_records(self, records: sqlalchemy.engine.CursorResult) -> Any
  • Behavior: Returns the first column in the first record from the database, even if multiple records or

dysql.mappers.KeyValueMapper

  • Import Path: from dysql.mappers import KeyValueMapper
  • Required Test Import Paths:
    • dysql.KeyValueMapper
  • Exact Test Import Statements:
    • from dysql import ( RecordCombiningMapper, SingleRowMapper, SingleColumnMapper, SingleRowAndColumnMapper, CountMapper, KeyValueMapper, )
  • Kind: class
  • Signature:
class KeyValueMapper(BaseMapper):
    def __init__(self, key_column=0, value_column=1, has_multiple_values_per_key=False)
    def map_records(self, records: sqlalchemy.engine.CursorResult) -> Any
    key_column: Any
    value_column: Any
    has_multiple_values_per_key: Any
  • Raises (implementation must reproduce these exact messages):
    • key and value columns cannot be the same
  • Behavior: :param key_column can be specified to determine what field to map to as the key for are keyed values

dysql.exceptions.DBNotPreparedError

  • Import Path: from dysql.exceptions import DBNotPreparedError
  • Required Test Import Paths:
    • dysql.DBNotPreparedError
  • Exact Test Import Statements:
    • from dysql import ( sqlquery, DBNotPreparedError, set_default_connection_parameters, QueryData, set_database_init_hook, )
  • Kind: exception
  • Signature:
class DBNotPreparedError(Exception)
  • Behavior: DB Not Prepared Error

dysql.databases._DEFAULT_CONNECTION_PARAMS_BY_KEY

  • Import Path: from dysql.databases import _DEFAULT_CONNECTION_PARAMS_BY_KEY
  • Required Test Import Paths:
    • dysql.databases._DEFAULT_CONNECTION_PARAMS_BY_KEY
  • Exact Test Import Statements:
    • import dysql.connections
  • Kind: constant
  • Signature:
_DEFAULT_CONNECTION_PARAMS_BY_KEY: Any
  • Behavior: Module-level value required by the test import contract.

dysql

  • Import Path: dysql
  • Required Test Import Paths:
    • dysql
  • Exact Test Import Statements:
    • import dysql
  • Kind: module
  • Behavior: Module required during hidden-test collection.

Capability: Async-context database selection for multitenancy

Async-context database selection for multitenancy

Purpose

Multitenant deployments typically host one logical database per tenant. This capability lets a single pool of decorated data-access functions (@sqlquery, @sqlupdate, @sqlexists) serve every tenant: the calling async context declares which registered database key to use, and each decorated call resolves that key when it runs. The selection state lives in a contextvars.ContextVar (CURRENT_DATABASE_VAR, declared with default ""), so concurrent requests — each with its own context — can target different tenant databases simultaneously without thread-locals or argument plumbing.

How the pieces relate

  • set_current_database(database_key) stores the key in the context var for the current async context (a debug log records it).
  • reset_current_database() is a thin helper: it calls `set_current_database("", making the empty string the explicit "use the default" sentinel.
  • is_set_current_database_supported() is a deprecated compatibility shim that unconditionally returns True; older code guarded usage behind it, and it remains safe to call.
  • DatabaseContainerSingleton is a singleton dict that materializes a Database instance for any requested key once parameters are registered. Its current_database property resolves the effective key: the context var's value, or — when that value is empty/falsy and at least one parameter set exists — the first key registered in _DEFAULT_CONNECTION_PARAMS_BY_KEY (insertion order of the defaultdict). If nothing is registered at all, no fallback applies and container access raises immediately (see the failure modes below).
  • Init hook contract. set_database_init_hook (which delegates to Database.set_init_hook) registers a single class-level hook shared by every Database instance: one global hook across all keys, and a later registration replaces it globally. It fires exactly once per engine creation, as hook(database_name, engine), where database_name is the database value from the connection parameters registered under the resolved key — not the context-selected tenant key; when database_key differs from the database name, the hook observes the latter (a test-sensitive distinction).
  • Inside dysql.connections, _ConnectionManager reads _DATABASE_CONTAINER.current_database.engine at decorated-function invocation time. That engine is cached per key on first use, and the hook fires only at that lazy creation.

Realistic workflow

  1. Register one connection parameter set per tenant, each with a distinct database_key: set_default_connection_parameters(host, user, password, database, database_key="tenant_a"), then again for "tenant_b". Omitting database_key registers the database name as the key.
  2. In the request coroutine, call set_current_database("tenant_b") before invoking decorated functions; call reset_current_database() when done (or rely on context isolation).
  3. Every @sqlquery/@sqlupdate/@sqlexists call in that coroutine acquires its connection from the selected tenant's engine.

State changes, ordering, and defaults

  • Order matters, with two distinct failure modes. set_default_connection_parameters must run before any decorated call resolves its database. With zero registered parameter sets, the failure is eager: DatabaseContainer.__getitem__ (and therefore current_database) raises DBNotPreparedError with Unable to connect to a database, set_default_connection_parameters must first be called during key resolution itself — no Database object is created and .engine is never reached. With parameters registered but the selected key missing, the container does return a Database object and the failure is lazy: its engine property raises DBNotPreparedError with No connection parameters found for database key '<key>' at first engine access (engine-creation time). Because the per-key check happens at engine creation, registering the missing key between set_current_database and the first decorated call avoids the error entirely.
  • Default fallback is positional. With no current key set, the first-registered tenant wins — registration order is behavior, not cosmetic. Tests that depend on default routing must control registration order.
  • Resolution is per call, not per process. The key is read each time a decorated function is invoked; switching tenants mid-coroutine changes subsequent calls immediately. But the tenant is fixed for the lifetime of one decorated call: the connection (and transaction, for @sqlupdate) binds to one engine.

Concurrency semantics

ContextVar.set affects only the current context. asyncio tasks copy the context at creation, so a key set inside one task is invisible to siblings and the parent; a key set in a parent before spawning tasks is visible to them. Within one coroutine, the set persists until reset or coroutine completion. Prefer set-at-request-start / reset-at-request-end, or run tenant work inside contextvars.copy_context().run for strict scoping.

Edge cases and test-sensitive behavior

  • reset_current_database() is exactly set_current_database("") — tests can assert equivalence via the context var.
  • The empty string, not None, is the reset sentinel; the fallback check is on falsiness of the retrieved value.
  • Engine and cache lifetime. Per-key Database entries persist for the life of the process in the singleton — there is no eviction path. Alternating tenants reuses each tenant's engine, and a given key's init hook fires once per process. Re-registering set_default_connection_parameters for an existing key updates the stored parameter set, and an engine not yet created picks up the new parameters at creation — but a materialized engine keeps its original URL/pool settings and the hook does not re-fire. Tests that need new parameters to take effect must use a fresh key or a fresh container.
  • is_set_current_database_supported() returning True always means no runtime capability probe is needed on modern Pythons (the historical Python 3.7+ restriction is moot).
  • Selecting an unregistered key (with other parameters registered) fails lazily at first engine access with the exact DBNotPreparedError message above — not at set_current_database time, which never validates the key; the zero-registration case instead fails eagerly during container resolution, as described above.

Exact API Reference

dysql.databases.is_set_current_database_supported

  • Import Path: from dysql.databases import is_set_current_database_supported
  • Required Test Import Paths:
    • dysql.databases.is_set_current_database_supported
  • Exact Test Import Statements:
    • from .databases import ( is_set_current_database_supported, set_current_database, set_default_connection_parameters, )
    • import dysql.connections
  • Signature:
def is_set_current_database_supported() -> bool
  • Behavior: Deprecated, left in for backwards compatibility but always returns true.

dysql.databases.set_current_database

  • Import Path: from dysql.databases import set_current_database
  • Required Test Import Paths:
    • dysql.databases.set_current_database
  • Exact Test Import Statements:
    • from .databases import ( is_set_current_database_supported, set_current_database, set_default_connection_parameters, )
    • import dysql.connections
  • Signature:
def set_current_database(database_key: str) -> None
  • Behavior: Sets the current database key, may be used for multitenancy. This is only supported on Python 3.7+. This uses

dysql.databases.reset_current_database

  • Import Path: from dysql.databases import reset_current_database
  • Required Test Import Paths:
    • dysql.databases.reset_current_database
  • Exact Test Import Statements:
    • import dysql.connections
  • Signature:
def reset_current_database() -> None
  • Behavior: Helper method to reset the current database to the default. Internally, this calls set_current_database with

dysql.databases.Database

  • Import Path: from dysql.databases import Database
  • Required Test Import Paths:
    • dysql.databases.Database
  • Exact Test Import Statements:
    • import dysql.connections
  • Kind: class
  • Signature:
class Database:
    def __init__(self, database_key: Optional[str]) -> None
    @classmethod
    def set_init_hook(cls, hook_method: Callable[[Optional[str], sqlalchemy.engine.Engine], None]) -> None
    @property
    def engine(self) -> sqlalchemy.engine.Engine
    database: Any

dysql.databases.DatabaseContainerSingleton

  • Import Path: from dysql.databases import DatabaseContainerSingleton
  • Required Test Import Paths:
    • dysql.databases.DatabaseContainerSingleton
  • Exact Test Import Statements:
    • from dysql import set_default_connection_parameters, databases
    • import dysql.connections
  • Kind: class
  • Signature:
class DatabaseContainerSingleton(DatabaseContainer):
    def __new__(cls, *args, **kwargs) -> 'DatabaseContainer'
    def __getitem__(self, database: Optional[str]) -> Database
    @property
    def current_database(self) -> Database
  • Behavior: All instantiations of this class will result in the same instance every time due to the override of

Capability: QueryData construction with parameterized list templates

Where this capability sits

QueryData is the return contract for every @sqlquery / @sqlupdate / @sqlexists function: it stores the SQL text plus two optional dictionaries — query_params for classic :name binds and template_params for list templates — as plain attributes, exactly as given. get_query_data is the single expansion point the decorators call to turn that object into the (query, params) pair handed to the engine. It is pure: it never mutates the QueryData or either dict; it builds a fresh params mapping and returns a new query string.

Expansion pipeline

  1. Type gate. Anything that is not a QueryData instance raises QueryDataError ("SQL annotated methods must return an instance of QueryData for query information"). This is what backstops decorated functions that accidentally return raw strings or tuples.
  2. Template scan and validation. A regex finds every {in__col}, {not_in__tbl.col}, {values__name} placeholder (names are [A-Za-z_]+, with at most one dotted table qualifier). Each found key must have a non-None entry in template_params; the first missing key in left-to-right order aborts with ListTemplateException("Missing template keys ['<key>']") — a query with several missing templates reports only the first one. An explicit None template value counts as missing, and an absent entry is indistinguishable from it.
  3. Whitespace normalization. Each matched placeholder region is stripped of its surrounding spaces before expansion; the generated fragment is then inserted wrapped in exactly one leading and one trailing space. So WHERE{in__x}AND renders as WHERE x IN ( ... ) AND, and writing a space on either side of the token does not produce doubles. Note the template itself emits the column name — you write WHERE {in__status}, never WHERE status {in__status}.
  4. Param merge. query_params are copied in first, then each template's generated params are applied in placeholder order, so template keys win collisions with query_params.

Template semantics

  • in__: col IN ( :key_0, :key_1, ... ). An empty list degrades to the predicate 1 <> 1 with no params added (matches nothing).
  • not_in__: same shape with NOT IN; an empty list becomes 1 = 1 with no params (matches everything).
  • values__: VALUES ( :key_0_0, :key_0_1, ... ), ( :key_1_0, ... ) for bulk inserts. Failing values split into two cases: a None (or absent) template_params entry never reaches the generator — it is caught by the step-2 missing-key check and raises ListTemplateException("Missing template keys ['values__<key>']"). Only a falsy-but-non-None value (empty list/tuple/set/str, 0) passes validation and reaches TemplateGenerators.values, which raises ListTemplateException with "Must have values for template", where <column> is the column part after __.

Parameter naming is deterministic but not collision-safe. get_query_data passes the full template key as legacy_key; when building param names, dots are replaced with underscores, so {in__table.status} produces SQL table.status IN (...) with params in__table_status_0, ... Stripping of [ ,()] characters happens only for multi-column helper keys (in_multi_column / not_in_multi_column); regex-derived template keys cannot contain those characters, so it never applies to plain template expansion. The dot-to-underscore mapping can collide: {in__a.b} and {in__a_b} both produce in__a_b_0, so the later placeholder's params overwrite the earlier one's (the SQL text itself still differs). A bare str value is wrapped into a one-element list before expansion; lists, tuples, and sets are re-enumerated safely (set order is iteration order).

Row semantics depend on shape:

  • in__/not_in__ with all-tuple elements: each element is treated as a row with a two-level index (key_<row>_<col>); the fragment is multiple parenthesized groups after IN — col IN ( :k_0_0, :k_0_1 ), ( :k_1_0, :k_1_1 ) — and the extra outer wrap ((( ... ))) is added only by the multi-column helpers.
  • values__ rows: list/tuple/set rows get key_<row>_<col>; a scalar row gets the single-level name key_<row> (VALUES ( :values__x_0 ), ...).
  • Mixed in__/not_in__ lists: the first non-tuple element aborts row treatment and flattens the entire original list to single-level key_<i> params, passing any tuple through as a raw param value (e.g. [1, (2,3)] yields in__k_0=1, in__k_1=(2,3)).
  • Row detection keys off the effective key starting with values, so a direct values('actors', [[1,2]]) call flattens rows to single-level actors_<i> params instead of two-level indexing.

For multi-column helpers, a key like (column_a, column_b) is cleaned to column_acolumn_b and the key list is wrapped in an extra parenthesis: (column_a, column_b) IN (( :column_acolumn_b_0_0, ... )). When the generators are called directly without legacy_key, names derive from the bare column name instead.

Workflow notes and edge cases

  • query_params given as a list of dicts makes the decorator issue one query per entry; template_params exists precisely to keep it a single statement.
  • Duplicate placeholders in one query are all replaced (string replace hits every occurrence) and regenerate identical params, so duplication is idempotent.
  • Empty-list degradation is intentional: WHERE {in__a} OR {in__b} with one empty list still yields a runnable statement (... OR 1 <> 1 ) rather than an error.
  • The placeholder grammar admits column parts that themselves contain a double underscore, e.g. {in__a__b} or {in__a__b.c}. get_query_data splits each validated key on __ and unpacks exactly two parts, so such keys — even with template_params correctly supplied — surface as an unpacking ValueError ("too many values to unpack") from get_query_data, not a ListTemplateException.
  • TemplateGenerators is also usable standalone to build fragments by hand; get_template dispatches only in, not_in, and values, returning None for anything else (the regex-driven path can never hit that).
  • get_query_data is exactly what the decorators invoke, so unit tests can exercise template expansion without a database by calling it directly on a hand-built QueryData.

Exact API Reference

dysql.query_utils.TemplateGenerators

  • Import Path: from dysql.query_utils import TemplateGenerators
  • Required Test Import Paths:
    • dysql.query_utils.TemplateGenerators
  • Exact Test Import Statements:
    • from dysql.query_utils import TemplateGenerators, ListTemplateException
  • Kind: class
  • Signature:
class TemplateGenerators:
    @classmethod
    def get_template(cls, name: str)
    @staticmethod
    def in_column(name: str, values: Union[str, Iterable[str]], legacy_key: str=None, is_multi_column: bool=False) -> Tuple[str, Optional[dict]]
    @staticmethod
    def in_multi_column(name: str, values: Union[str, Iterable[str]], legacy_key: str=None)
    @staticmethod
    def not_in_column(name: str, values: Union[str, Iterable[str]], legacy_key: str=None, is_multi_column: bool=False) -> Tuple[str, Optional[dict]]
    @staticmethod
    def not_in_multi_column(name: str, values: Union[str, Iterable[str]], legacy_key: str=None)
    @staticmethod
    def values(name: str, values: Union[str, Iterable[str]], legacy_key: str=None) -> Tuple[str, Optional[dict]]
  • Behavior: Functions in this class help to return a tuple which contains the query template along with

dysql.query_utils.QueryData

  • Import Path: from dysql.query_utils import QueryData
  • Required Test Import Paths:
    • dysql.QueryData
    • dysql.query_utils.QueryData
  • Exact Test Import Statements:
    • from .query_utils import QueryData
    • from dysql import ( sqlquery, DBNotPreparedError, set_default_connection_parameters, QueryData, set_database_init_hook, )
    • from dysql import ( sqlupdate, sqlquery, DbMapResult, CountMapper, SingleRowMapper, QueryData, QueryDataError, )
    • from dysql import QueryData, sqlquery
    • from dysql import QueryData, sqlupdate, QueryDataError
    • from dysql import sqlexists, QueryData
  • Kind: class
  • Signature:
class QueryData:
    def __init__(self, query: str, query_params: dict=None, template_params: dict=None)
    query: Any
    query_params: Any
    template_params: Any
  • Behavior: Query data is a wrapper class that allows us to pass back information for a query with more

dysql.query_utils.get_query_data

  • Import Path: from dysql.query_utils import get_query_data
  • Signature:
def get_query_data(data: QueryData) -> Tuple[str, dict]
  • Behavior: Retrieves the query and parameters from a QueryData object.

dysql.query_utils.QueryDataError

  • Import Path: from dysql.query_utils import QueryDataError
  • Required Test Import Paths:
    • dysql.QueryDataError
  • Exact Test Import Statements:
    • from dysql import ( sqlupdate, sqlquery, DbMapResult, CountMapper, SingleRowMapper, QueryData, QueryDataError, )
    • from dysql import QueryData, sqlupdate, QueryDataError
  • Kind: exception
  • Signature:
class QueryDataError(Exception)
  • Behavior: This exception is thrown when we expect a QueryData object but end up with something different

dysql.query_utils.ListTemplateException

  • Import Path: from dysql.query_utils import ListTemplateException
  • Required Test Import Paths:
    • dysql.query_utils.ListTemplateException
  • Exact Test Import Statements:
    • from dysql.query_utils import TemplateGenerators, ListTemplateException
    • import dysql
  • Kind: exception
  • Signature:
class ListTemplateException(Exception)
  • Behavior: List Template Exception

Capability: Declarative SQL decorators for selects, exists checks, and updates

Declarative SQL decorators: sqlquery, sqlexists, sqlupdate

Shared execution model

Each decorator turns a plain function into an executor. At call time the wrapper:

  1. Acquires a fresh connection from the current database container's engine and applies isolation_level (default READ_COMMITTED) through execution_options — before any transaction begins.
  2. Calls the wrapped function with the caller's arguments. The function is a query supplier: it must return (or, for sqlupdate generators, yield) a QueryData. Any other payload — including the raw tuple shown in some docstring examples — raises QueryDataError with message SQL annotated methods must return an instance of QueryData for query information.
  3. Normalizes the payload with get_query_data: list templates ({in__col}, {not_in__col}, {values__x}) are validated against template_params (missing or empty → ListTemplateException), expanded in place, and their generated bind parameters merged into the query params.
  4. Executes through sqlalchemy.text on that connection. Falsy params become {}; a DbMapResult passed as params is converted with .raw().
  5. Restores state on context exit: sqlquery/sqlexists simply close the connection; sqlupdate commits or rolls back first.

Decorator syntax: only the called form executes. Every factory unconditionally returns its inner decorator closure, never dispatching on whether it received a function, so bare usage binds the name to the unapplied closure: calling it never runs SQL — a bare sqlexists call with positional args returns the inner wrapper (no bool), otherwise TypeError. Tests must use the called form.

Decorator metadata note: the wrappers invoke functools.wraps incorrectly (the partial is never applied), so the replacement function does not preserve __name__, __doc__, etc. Tests must not rely on the original function's metadata surviving decoration.

@sqlquery(mapper=..., isolation_level=...)

  • Read path with no explicit transaction: statements run on a plain connection, results are returned immediately.
  • mapper may be a BaseMapper subclass (instantiated fresh per call) or an already-built instance; None defaults to RecordCombiningMapper. The wrapper returns mapper.map_records(records) directly, so the return type follows the mapper: list of DbMapResult rows for the default, scalars for SingleColumnMapper, first row for SingleRowMapper, first scalar for CountMapper (SingleRowAndColumnMapper; None when the result set is empty, not 0), dicts for KeyValueMapper.
  • Default-mapper merging: RecordCombiningMapper collapses records sharing the key columns (default ['id'] from DbMapResultBase.get_key_columns) into one DbMapResult, so a JOIN returning several child rows per parent yields one result per parent; if any key column is absent from a record, no combining happens and one result is produced per row. Expected result counts for multi-row queries are test-sensitive.
  • Mapping failures surface as MapperError from the mapper layer.

DbMapResult value semantics

  • The constructor always ensures an 'id' key, defaulting to None.
  • raw() deletes the 'id' entry when its value is None, so a row without an id serializes without that key — including when a DbMapResult is passed as query params.
  • has(field) is true only when the stored value is not None: an explicitly-None field counts as absent.
  • get(field, default) returns the default only when the key is missing, not when the value is None.

@sqlexists / @sqlexists(...)

  • Use the called form (see decorator syntax above); bare decoration never executes.
  • After normalization the SQL is rewritten: leading whitespace is stripped; a query already starting with SELECT EXISTS becomes SELECT 1 WHERE EXISTS ...; anything not starting with SELECT 1 WHERE EXISTS is wrapped as SELECT 1 WHERE EXISTS ( <query> ). A query that already begins with SELECT 1 WHERE EXISTS passes through untouched.
  • The rewritten statement runs with .scalar() and the decorator returns result == 1 — a strict Python bool. No matching row yields NULL → None → False; a value other than 1 also yields False. Missing rows never raise.

@sqlupdate(...)

  • Opens an explicit transaction before executing. Clean exit commits; any exception logs the error, rolls back, and propagates — on_success is skipped on failure.
  • Statement ordering: optional SET FOREIGN_KEY_CHECKS=0 → the wrapped function's statements → SET FOREIGN_KEY_CHECKS=1 → injected-kwarg cleanup → commit (context exit) → on_success(*args, **kwargs). Because the FK re-enable runs inside the transaction, a rollback leaves a clean state (the connection is discarded).
  • get_last_insert_id is injected only if the wrapped function's signature declares a parameter with that exact name. The decorator supplies a lambda that executes SELECT LAST_INSERT_ID() and returns its scalar; the kwarg is removed before on_success, so success handlers never see it.
  • Generator functions drive multi-statement flows: every yielded value is normalized and executed sequentially inside the single open transaction, all before commit. If a yielded query_params is a list, the same query executes once per dict — useful for batch child rows. In non-generator updates, a list query_params raises Exception with message Params must not be a list.
  • Typical generator shape: declare def fn(data, get_last_insert_id=None), yield the parent insert, call get_last_insert_id(), then yield child statements referencing that id.

Cross-cutting edge cases

  • Nothing happens at decoration time; all work is deferred to the first call, so an uninitialized database fails inside the wrapper (prepare defaults with set_default_connection_parameters beforehand).
  • Template placeholders are matched by exact key; a template_params entry that is present but None counts as missing and raises ListTemplateException.
  • sqlquery mapping consumes the whole cursor; pick the mapper to match the query shape.
  • sqlexists docstrings show bare @sqlexists decoration and bare string/tuple payloads, but neither works as shown: use the called decorator form and always supply QueryData.

Exact API Reference

dysql.connections.sqlquery

  • Import Path: from dysql.connections import sqlquery
  • Required Test Import Paths:
    • dysql.connections.sqlquery
    • dysql.sqlquery
  • Exact Test Import Statements:
    • from .connections import sqlquery
    • from dysql import ( sqlquery, DBNotPreparedError, set_default_connection_parameters, QueryData, set_database_init_hook, )
    • from dysql import ( sqlupdate, sqlquery, DbMapResult, CountMapper, SingleRowMapper, QueryData, QueryDataError, )
    • from dysql import QueryData, sqlquery
  • Signature:
def sqlquery(mapper: Union[BaseMapper, Type[BaseMapper]]=None, isolation_level: str='READ_COMMITTED')
  • Behavior: query allows for defining a parameterize select query that is then executed

dysql.connections.sqlexists

  • Import Path: from dysql.connections import sqlexists
  • Required Test Import Paths:
    • dysql.sqlexists
  • Exact Test Import Statements:
    • from dysql import sqlexists, QueryData
  • Signature:
def sqlexists(isolation_level='READ_COMMITTED')
  • Behavior: exists query allows for defining a parameterize select query that is

dysql.connections.sqlupdate

  • Import Path: from dysql.connections import sqlupdate
  • Required Test Import Paths:
    • dysql.sqlupdate
  • Exact Test Import Statements:
    • from dysql import ( sqlupdate, sqlquery, DbMapResult, CountMapper, SingleRowMapper, QueryData, QueryDataError, )
    • from dysql import QueryData, sqlupdate, QueryDataError
  • Signature:
def sqlupdate(isolation_level='READ_COMMITTED', disable_foreign_key_checks=False, on_success=None)
  • Raises (implementation must reproduce these exact messages):
    • Params must not be a list
  • Behavior: :param isolation_level should specify whether we can read data from transactions that are not

dysql.mappers.DbMapResultBase

  • Import Path: from dysql.mappers import DbMapResultBase
  • Signature:
class DbMapResultBase:
    def get_key_columns(cls)
    def create_instance(cls, *args, **kwargs) -> 'DbMapResultBase'
    def map_record(self, record: sqlalchemy.engine.Row) -> None
    def raw(self) -> dict
    def has(self, field: str) -> bool
    def get(self, field: str, default: Any=None) -> Any

dysql.mappers.DbMapResult

  • Import Path: from dysql.mappers import DbMapResult
  • Required Test Import Paths:
    • dysql.DbMapResult
  • Exact Test Import Statements:
    • from dysql import ( sqlupdate, sqlquery, DbMapResult, CountMapper, SingleRowMapper, QueryData, QueryDataError, )
    • from dysql import DbMapResult
  • Kind: class
  • Signature:
class DbMapResult(DbMapResultBase):
    def __init__(self, **kwargs)
    def __getitem__(self, field: str) -> Any
    def __setitem__(self, field: str, value: Any) -> None
    def __str__(self) -> str
    def map_record(self, record: sqlalchemy.engine.Row) -> None
    def raw(self) -> dict
    def has(self, field: str) -> bool
    def get(self, field: str, default: Any=None) -> Any
    id: Any
    @classmethod
    def get_key_columns(cls)
    @classmethod
    def create_instance(cls, *args, **kwargs) -> 'DbMapResultBase'

dysql.connections

  • Import Path: from dysql import connections
  • Required Test Import Paths:
    • dysql.connections
  • Exact Test Import Statements:
    • import dysql.connections
  • Kind: module
  • Behavior: Module required during hidden-test collection.

dysql.mappers.MapperError

  • Import Path: from dysql.mappers import MapperError
  • Required Test Import Paths:
    • dysql.mappers.MapperError
  • Exact Test Import Statements:
    • from dysql.mappers import MapperError
  • Kind: exception
  • Signature:
class MapperError(Exception)

Capability: Query result mapping to Python objects

Purpose

The mapping layer converts a SQLAlchemy CursorResult into ordinary Python values: lists of domain objects, a single object, a list of scalars, one scalar, or a keyed dictionary. A decorator such as @sqlquery executes the statement and hands the cursor to the mapper instance supplied through its mapper argument; whatever map_records returns becomes the decorated function's return value. Mappers are pure transformers over an iterable of rows — they never open connections or run SQL.

The result-object contract

DbMapResultBase defines what a mapped record must expose: classmethod get_key_columns() (defaults to ["id"]), classmethod factory create_instance() (defaults to calling the constructor — override to build objects another way), and abstract map_record(record), raw(), has(field), and get(field, default=None).

DbMapResult is the stock implementation, and its exact behaviors are test-sensitive:

  • It is constructed from keyword arguments; any falsy id value is replaced with None. Every instance therefore gets an id attribute defaulting to None, and this applies even when the query did select id — a genuinely selected id of 0 or '' is overwritten with None.
  • Dict-style access: subscript reads go through dict.get, so result["missing"] silently returns None instead of raising KeyError; only assignment writes through to __dict__. str(result) prints that dict.
  • map_record copies every column of a row onto the object. Calling it again with another row overwrites per column — it accumulates nothing. This overwrite-on-repeat is the mechanism behind record combining, and it means the last row seen for a key wins each column value.
  • has(field) is None-sensitive: a selected column holding SQL NULL reports has(...) == False.
  • get(field, default) is a plain dict lookup with default.
  • raw() recurses: nested DbMapResultBase values (including inside lists) are unwrapped to dicts. It deletes the id key whenever its value is None — so besides the synthetic placeholder, a real id column that came back as SQL NULL is stripped too, and a round-trip to plain dicts never leaks a null id.

Custom result classes subclass DbMapResult (or the abstract base), overriding get_key_columns for composite keys and/or create_instance for alternative construction. Whatever class is passed as record_mapper must satisfy the DbMapResultBase contract (get_key_columns, create_instance, map_record, raw, has, get). Separately, the dysql.annotations module provides FromCSVToList (from dysql.annotations import FromCSVToList), a pydantic validation annotation of the form Annotated[T, BeforeValidator(...)] that turns a CSV string into a list of stripped strings: an empty or None value becomes None, values that are already lists pass through unchanged, and any other non-string value is wrapped as [value]. It is an independent input-validation helper with no connection to the mapper layer — it is not a record mapper and cannot be passed as record_mapper.

Mapper strategies

  • RecordCombiningMapper(record_mapper=DbMapResult) — groups rows by hash(tuple(record[c] for c in get_key_columns())) into an OrderedDict, so first-appearance order is preserved. A row is not combined when any key column is missing from it or when get_key_columns() returns empty; such rows get their own positional entry. The truthiness check is applied to the combined hash value itself, so individual falsy key values (e.g. id=0) do not cause separate entries — hash((0,)) is nonzero and those rows still group normally. The positional-entry branch is reached only in the rare case where the multi-column key's combined hash is itself falsy.
  • SingleRowMapper(record_mapper=DbMapResult) — maps and returns the first row only; None on an empty result; record_mapper=None returns the raw first row. Later rows stay unconsumed in the cursor.
  • SingleColumnMapper — a list of each row's first column value; extra columns ignored; [] when empty.
  • SingleRowAndColumnMapper — the first column of the first row, else None. CountMapper is an unchanged subclass: use it for SELECT COUNT(*) to get a scalar (or None on empty).
  • KeyValueMapper(key_column=0, value_column=1, has_multiple_values_per_key=False) — dict keyed by positional column index (integers, not names). Construction validates key_column != value_column and raises MapperError immediately, so a bad configuration fails before any query runs. In default mode duplicate keys overwrite (last row per key wins); with has_multiple_values_per_key=True it returns a defaultdict(list) with values appended in row order.

Custom mappers

Subclass BaseMapper and implement map_records(records) -> Any; the decorator passes the return value through unchanged, so any shape is allowed. A shipped mapper's map_records only reads self.record_mapper (or constructor-set columns), so instances are stateless across calls and safe to share between decorated functions.

Ordering, defaults, edge cases

Rows are consumed in cursor order; grouped results keep first-seen key order. Empty inputs yield: [] (RecordCombiningMapper, SingleColumnMapper), None (SingleRowMapper, SingleRowAndColumnMapper/CountMapper), and for KeyValueMapper either {} (default mode) or an empty defaultdict(list) (multi-value mode). Remember the asymmetric gotchas: combining overwrites columns rather than collecting them (use KeyValueMapper with multi-values for one-to-many), has() lies about NULL fields, raw() silently drops any id whose value is None (synthetic or genuinely NULL), falsy selected ids become None, and subscript reads return None for absent fields.

Exact API Reference

dysql.mappers.RecordCombiningMapper

  • Import Path: from dysql.mappers import RecordCombiningMapper
  • Required Test Import Paths:
    • dysql.RecordCombiningMapper
  • Exact Test Import Statements:
    • from dysql import ( RecordCombiningMapper, SingleRowMapper, )
    • from dysql import ( RecordCombiningMapper, SingleRowMapper, SingleColumnMapper, SingleRowAndColumnMapper, CountMapper, KeyValueMapper, )
  • Kind: class
  • Signature:
class RecordCombiningMapper(BaseMapper):
    def __init__(self, record_mapper: Optional[Type[DbMapResultBase]]=DbMapResult)
    def map_records(self, records: sqlalchemy.engine.CursorResult) -> Any
    record_mapper: Any
  • Behavior: Creates one or more mapped results from multiple records. This returns the same or less number

dysql.mappers.SingleRowMapper

  • Import Path: from dysql.mappers import SingleRowMapper
  • Required Test Import Paths:
    • dysql.SingleRowMapper
  • Exact Test Import Statements:
    • from dysql import ( RecordCombiningMapper, SingleRowMapper, )
    • from dysql import ( RecordCombiningMapper, SingleRowMapper, SingleColumnMapper, SingleRowAndColumnMapper, CountMapper, KeyValueMapper, )
    • from dysql import ( sqlupdate, sqlquery, DbMapResult, CountMapper, SingleRowMapper, QueryData, QueryDataError, )
  • Kind: class
  • Signature:
class SingleRowMapper(BaseMapper):
    def __init__(self, record_mapper: Optional[Type[DbMapResultBase]]=DbMapResult)
    def map_records(self, records: sqlalchemy.engine.CursorResult) -> Any
    record_mapper: Any
  • Behavior: Returns a single mapped result from one or more records. The first record is returned even if

dysql.annotations.FromCSVToList

  • Import Path: from dysql.annotations import FromCSVToList
  • Required Test Import Paths:
    • dysql.annotations.FromCSVToList
  • Exact Test Import Statements:
    • from dysql.annotations import FromCSVToList
  • Kind: constant
  • Signature:
FromCSVToList: Any
  • Behavior: Module-level value required by the test import contract.

dysql.mappers.CountMapper

  • Import Path: from dysql.mappers import CountMapper
  • Required Test Import Paths:
    • dysql.CountMapper
    • dysql.mappers.CountMapper
  • Exact Test Import Statements:
    • from .mappers import CountMapper
    • from dysql import ( RecordCombiningMapper, SingleRowMapper, SingleColumnMapper, SingleRowAndColumnMapper, CountMapper, KeyValueMapper, )
    • from dysql import ( sqlupdate, sqlquery, DbMapResult, CountMapper, SingleRowMapper, QueryData, QueryDataError, )
  • Kind: class
  • Signature:
class CountMapper(SingleRowAndColumnMapper):
    def map_records(self, records: sqlalchemy.engine.CursorResult) -> Any
  • Behavior: Alias for SingleRowAndColumnMapper, may be used to easily return the result of a count query.

Capability: Pydantic model result mapping

Pydantic model result mapping

Purpose

DbMapResultModel lets rows from a query land directly on an annotated pydantic model. You declare typed fields plus optional _-prefixed metadata class attributes, then hand the model to a record mapper (record_mapper=MyModel); the library fills each field without per-field mapping code. Its real job is collapsing multi-row joins — one logical entity spread over N rows — into one model instance whose list, set, and dict fields aggregate across rows.

How the pieces fit a realistic workflow

  1. Declare the model. Plain annotated fields map column-for-column. Metadata attributes redirect columns into aggregations:
    • _list_fields / _set_fields: the DB column holds a scalar per row; each record appends/adds it to the target collection field.
    • _csv_list_fields: the column holds comma-separated text; each record's string is split on ",", whitespace-stripped, pre-validated against the field annotation via TypeAdapter, then extended into the list.
    • _json_fields: the column holds a JSON document; parsed via TypeAdapter(annotation).validate_json, but only while the instance is not yet in merge mode (see validation timing below).
    • _dict_key_fields maps DB column name → model dict field; _dict_value_mappings is the reverse view (model dict field → DB value column). Together they build {key_value: value_value} entries, and the raw value columns are removed from the model.
  2. Instantiate via the mapper. create_instance() builds the object with model_construct, so creation itself never validates — validation is deferred.
  3. Merge rows. The mapper calls map_record(record) once per row. The first call collects the row into a dict and runs it through self.__init__, so full pydantic validation and coercion execute exactly once (e.g. field_bool: 1 becomes True). Every later call mutates __dict__ directly — no revalidation — extending/appending/adding into the existing collections.

State and ordering

  • _has_been_mapped() is bool(model_fields_set): anything set by the first __init__ flips the instance into merge mode. This is why create_instance() (no fields set) still counts as "not mapped".
  • Within a row, record keys are processed in their given order with classification precedence list → csv → json → set → dict-key → plain. Columns matching nothing are written on the first record (pydantic ignores extras) and skipped on later records.
  • After each row, every DB column named in _dict_value_mappings is popped unconditionally, so value columns never leak into the output even when no dict mapping ran.
  • Row grouping is the mapper's responsibility: SingleRowMapper takes only the first record; RecordCombiningMapper re-invokes map_record for every row sharing the identity key. The key defaults to column id; override get_key_columns() (e.g. return ["a", "b"]) for composite keys — grouping hashes the full key tuple, so a=1,b=test and a=1,b=othertest are distinct instances. If any key column is missing from a record, no combining happens: that row gets its own freshly constructed instance, so a null/absent key silently fragments one entity into many results (each list/set/dict then holds a single row's values).

Defaults and edge cases (test-sensitive)

  • Null vs falsy: _list_fields, _set_fields, and dict entries skip only None values — falsy non-None values (0, False, "") are appended/added normally. The dict path checks only the value column; the key column is never checked, so a None key with a non-None value still yields a {None: value} entry. CSV and JSON skip any falsy value, and CSV's falsy check precedes the str() coercion (numeric 0/False CSV cells are dropped too). Skipped values never seed or extend a collection, so collection fields must declare defaults (List[str] = [], Set[str] = set(), Dict[str, Any] = {}) or first-row validation fails when columns are nullable or absent. An Optional[List[str]] = None field stays None on empty input; a field defaulted to [] stays [].
  • CSV: empty strings produce no value (defaults apply); values are str()-coerced before splitting; duplicates are not deduped — mapping the same row twice doubles the entries. A None in the first record followed by data later still aggregates in row order.
  • Validation timing: CSV elements are validated on every record (via TypeAdapter.validate_python against the field annotation), so a bad element in any later row raises ValidationError even though merging itself skips validation. JSON differs: TypeAdapter.validate_json runs only while _has_been_mapped() is false — practically the first record that sets any field. Later records' JSON columns are ignored entirely: no parse, no validation, no aggregation, so the first (and only) parsed JSON document wins, even if the seeding record's JSON column was null and a later record's is valid. All other field types are validated only on the first record — per-item validation of list/set/dict content beyond CSV must happen outside pydantic.
  • Read-back: raw() returns model_dump() and is the canonical comparison form in tests; has(field) checks __dict__ presence; get(field, default) reads without raising or triggering validation.

Non-obvious behavior

Aggregation order follows input row order, so merged results are deterministic. Dict key/value wiring is asymmetric and easy to get backwards: _dict_key_fields is keyed by DB name, _dict_value_mappings by model name. Mismatches fail loudly, not silently: _map_dict performs unguarded lookups, so a missing/mismatched model-name entry in _dict_value_mappings, or a value column absent from a record carrying the key column, raises KeyError on that row. The post-row pop over _dict_value_mappings values is unconditional, so any column named there is removed from the output even when no dict mapping ever ran. Metadata attributes are ordinary class attributes, so subclasses inherit and can extend them.

Exact API Reference

dysql.pydantic_mappers.DbMapResultModel

  • Import Path: from dysql.pydantic_mappers import DbMapResultModel
  • Required Test Import Paths:
    • dysql.pydantic_mappers.DbMapResultModel
  • Exact Test Import Statements:
    • from dysql.pydantic_mappers import DbMapResultModel
  • Kind: class
  • Signature:
class DbMapResultModel(BaseModel, DbMapResultBase):
    @classmethod
    def create_instance(cls, *args, **kwargs) -> 'DbMapResultModel'
    def map_record(self, record: sqlalchemy.engine.Row) -> None
    def raw(self) -> dict
    def has(self, field: str) -> bool
    def get(self, field: str, default: Any=None) -> Any
    @classmethod
    def get_key_columns(cls)
  • Behavior: Pydantic model that allows for results to be mapped into annotated fields without explicitly

Capability: Integration test database management

Integration test database management

Purpose

DbTestManagerBase and its MariaDB implementation give a test suite a disposable MariaDB/MySQL database whose schema is an exact structural copy of a reference schema. The manager is a context manager: entering provisions the database and wires the library's default connection parameters to it; exiting drops it unless retention was requested. Test modules declare a fixture and nothing else — no hand-written CREATE DATABASE, dump, or pool setup.

Lifecycle and strict ordering inside __enter__

  1. Destructive re-create. DROP DATABASE IF EXISTS {db_name} followed by CREATE DATABASE IF NOT EXISTS {db_name}, run through the mariadb CLI. db_name is caller-supplied, not unique per run — re-entering with the same name wipes any prior database, which is exactly what makes reruns deterministic.
  2. Schema duplication. If schema_db_name is set, a single shell pipeline mariadb-dump --no-data --routines {schema_db_name} | mariadb {db_name} copies structure and stored routines only; no table data is duplicated, so tests must seed their own rows.
  3. Connection defaults. set_default_connection_parameters(host, username, password, db_name, **connection_defaults) registers the test database. For MariaDbTestManager the forwarded defaults are fixed to port=3306, pool_size=3 (the library default is 10), charset="utf8", and echo_queries; the base class forwards any additional unknown kwargs into the same call, where they must match that function's parameters (pool_recycle, collation, database_key, ...). This happens before any engine exists, so it is the only point where defaults can take effect. Defaults merge, not replace: parameters are stored in a process-global registry keyed by database key and applied via a merge (update(locals())), so re-entering with the same db_name reuses the existing registry entry — only re-supplied parameters change, while stale optional parameters from prior entries (collation, pool_recycle, a previously supplied database_key) silently survive into the new entry.
  4. Current-database selection. is_set_current_database_supported() is a deprecated backwards-compatibility shim that always returns True, so set_current_database(db_name) is always invoked during provisioning — there is no code path that skips it. It makes the freshly created database the active context key, so plain @sqlquery / @sqlupdate / @sqlexists calls resolve to the test database with no extra configuration. Because resolution happens under db_name, any forwarded database_key must equal db_name: a divergent key registers the defaults under a different registry entry, so the first decorated query raises DBNotPreparedError ("No connection parameters found for database key ''") instead of failing at provisioning.
  5. Readiness wait. With a schema_db_name, _wait_for_tables_exist polls every 0.25 s until the information_schema.TABLES count of the schema source equals the count of the new database. The count check is itself a @sqlquery(mapper=CountMapper()), so it depends on steps 3–4 having completed — and it loops forever if the counts never converge (e.g. a partially failed dump); there is no poll timeout.

Docker handling

_is_running_in_docker checks for /.dockerenv and for the markers docker, kubepod, or lxc inside /proc/1/cgroup. The result inverts how shell commands run: outside docker, every command is wrapped as docker exec {docker_container} bash -c '...' because the database lives in a container named by docker_container; inside docker, commands run directly against host. All commands execute with shell=True, timeout=30, check=True, so a non-zero exit raises subprocess.CalledProcessError, aborting setup before any connection defaults are registered.

Defaults, environment, retention

  • Host and credentials come from environment variables with fallbacks: MARIA_HOST (localhost), MARIA_USERNAME (root), MARIA_PASSWORD (password), MARIA_CONTAINER_NAME (mariadb).
  • keep_db=True retains the database: __exit__ skips the DROP DATABASE IF EXISTS teardown so failed runs can be inspected. Retention is per-instance and opt-in.
  • The manager executes from dysql import set_default_connection_parameters, databases: set_default_connection_parameters is imported from the dysql package, while databases.set_current_database(...) and databases.is_set_current_database_supported() are reached as attributes of the imported databases module object (the dysql.databases submodule). What must remain importable when the test-manager module is collected is the dysql.databases module, plus set_default_connection_parameters remaining importable from dysql.

Test-sensitive behavior

  • The constructor performs no I/O; all side effects occur on __enter__.
  • Entering twice in one process with the same db_name recreates and wipes the database; since defaults merge rather than replace, stale optional parameters from the earlier entry remain in effect.
  • A forwarded database_key differing from db_name surfaces as DBNotPreparedError at the first decorated query, not at provisioning.
  • If the dump/create command fails, provisioning raises before defaults are set; subsequent decorated queries then fail with DBNotPreparedError rather than hanging.
  • Teardown drops the database via echo "DROP DATABASE IF EXISTS ..." | mariadb ..., subject to the same docker wrapping and 30 s timeout.
  • The dump/load runs as one pipeline in one execution context: both mariadb-dump and mariadb must be resolvable there (inside the container when wrapped).
  • Empty required connection values raise DBNotPreparedError from the defaults call, so blank env fallbacks fail fast at setup.

Exact API Reference

dysql.databases

  • Import Path: from dysql import databases
  • Required Test Import Paths:
    • dysql.databases
  • Exact Test Import Statements:
    • from dysql import set_default_connection_parameters, databases
  • Kind: module
  • Behavior: Module required during hidden-test collection.

Detailed Implementation Nodes

Node: Database connection parameter setup and engine initialization

Functional constraints

  • set_default_connection_parameters(host, user, password, database, database_key=None, port=3306, pool_size=10, pool_recycle=3600, echo_queries=False, charset="utf8", collation=None): raises DBNotPreparedError if any required value is falsy (message Database parameter "{name}" is not set or empty and is required); otherwise merges locals() into _DEFAULT_CONNECTION_PARAMS_BY_KEY[database_key or database]. Because locals() includes every parameter, a re-call for the same key rewrites all of it — omitted optionals revert to their declared defaults; the stored values are per-query defaults that QueryData may override at execution time.
  • Engine build is lazy, once per Database, and opens no connection: URL mysql+mysqlconnector://{user}:{password}@{host}:{port}/{database}?charset={charset} plus &collation={collation} when set; create_engine(url, pool_recycle=..., pool_size=..., echo=echo_queries, pool_pre_ping=True); then the init hook runs as hook(database_name, engine) (name, not key), only for engines built after set_database_init_hook was called. pool_pre_ping applies at checkout, so connection errors surface at first query execution, not engine build.
  • Exact error literals: container accessed before setup → Unable to connect to a database, set_default_connection_parameters must first be called; unknown key at engine build → No connection parameters found for database key '{key}'.
  • DatabaseContainer(dict).__getitem__ creates and caches Database(key); current_database uses the contextvar key (module-level ContextVar, context-local and inherited by context copies), else the first-registered key; DatabaseContainerSingleton yields one shared instance; params lookup is .get(key, {}) and never mutates the defaultdict; pool_pre_ping is always enabled; reset_current_database() sets "" in the calling context only.

Example (setup → first query triggers engine build)

from dysql import (sqlquery, set_default_connection_parameters,
                   set_database_init_hook, QueryData)

def on_engine(name, engine):        # fires once per engine, at build time
    print("engine ready for", name)

set_database_init_hook(on_engine)   # must run before the first engine build
set_default_connection_parameters(  # database_key defaults to "shop"
    host="db.local", user="svc", password="pw", database="shop",
    port=3306, pool_size=10, pool_recycle=3600, echo_queries=False)

@sqlquery()
def ping():
    return QueryData("SELECT 1")    # first ping() call builds and caches the engine

Node: Async-context database selection for multitenancy

Functional constraints

  • CURRENT_DATABASE_VAR is a contextvars.ContextVar("dysql_current_database", default=""); the empty string is the "default database" sentinel.
  • set_current_database(database_key) only stores the key in the context var — no validation against registered keys.
  • reset_current_database() calls set_current_database("").
  • is_set_current_database_supported() always returns True (deprecated shim).
  • Effective key resolution (DatabaseContainer.current_database via _get_current_database_key): context var value if truthy; else, when registrations exist, the first key inserted into _DEFAULT_CONNECTION_PARAMS_BY_KEY; otherwise the falsy context default.
  • Failure semantics split by registration state: DatabaseContainer.__getitem__ raises DBNotPreparedError("Unable to connect to a database, set_default_connection_parameters must first be called") eagerly, during resolution, when no parameter sets are registered — no Database instance is produced and .engine is never reached. With parameters registered but the key absent, __getitem__ materializes and caches a Database whose engine property raises DBNotPreparedError(f"No connection parameters found for database key '{self.database}'") at first engine access.
  • Init hook: set_database_init_hook delegates to the classmethod Database.set_init_hook, which stores the hook as a class attribute — one global hook shared by every Database instance, and re-registration replaces it for all keys. It fires once per engine creation as hook(database_name, engine), where database_name is the database name from the parameters registered under the resolved key, not the context-selected key.
  • Engines are lazy and cached on the per-key Database instance; container entries persist for the process (no eviction), so a materialized engine keeps its original URL/pool settings even if parameters are re-registered, and the hook does not re-fire — only engines not yet created read updated parameters. Tenant resolution happens at each decorated-call invocation (_ConnectionManager) and is fixed for that call's connection/transaction.
  • Context isolation: sets inside a task do not leak to siblings or the parent context.

Usage

from dysql.databases import (
    set_current_database, reset_current_database,
    is_set_current_database_supported,
)
from dysql import set_default_connection_parameters

set_default_connection_parameters("h1", "u", "p", "db_a", database_key="tenant_a")
set_default_connection_parameters("h2", "u", "p", "db_b", database_key="tenant_b")

async def handle():
    set_current_database("tenant_b")
    try:
        return await run_report_queries()
    finally:
        reset_current_database()

Node: QueryData construction with parameterized list templates

Functional constraints

  • get_query_data requires a QueryData instance; any other return value from an annotated function raises QueryDataError.
  • Every {in__…} / {not_in__…} / {values__…} token needs a non-None template_params entry; the first missing key (left to right) raises ListTemplateException ("Missing template keys …"). None and absent entries are both treated as missing; only falsy-but-non-None values reach the generator.
  • in__/not_in__ with an empty list emit 1 <> 1 / 1 = 1 with no params; values__ with an empty or otherwise falsy non-None value raises ListTemplateException from the generator.
  • Param names: the full template key with dots replaced by underscores, suffixed _0, _1, …; , ()/space removal applies only to multi-column keys (in_multi_column/not_in_multi_column). Rows: all-tuple in__/not_in__ values and list/tuple/set values__ rows use two-level key_<row>_<col>; scalar values__ rows use single-level key_<row>; mixed in__/not_in__ lists fall back to flat key_<i> with tuples passed through as values.
  • Expansion inserts exactly one space on each side of each generated fragment; surrounding whitespace around the token is stripped first, so the template must supply the column name itself.
  • query_params merge first; template params override on key collision. Neither input dict is mutated.
  • Direct TemplateGenerators calls (no legacy_key) name params from the bare column name; a bare str value is treated as a one-element list.
  • A template key whose column part contains a second __ (e.g. in__a__b) passes key validation but raises an unpacking ValueError when get_query_data splits on __.

Example

from dysql import QueryData
from dysql.query_utils import get_query_data

data = QueryData(
    "SELECT id FROM users WHERE {in__status} AND {not_in__u.name}",
    template_params={"in__status": ["on"], "not_in__u.name": ["bob"]},
)
query, params = get_query_data(data)
# query  == "SELECT id FROM users WHERE status IN ( :in__status_0 ) "
#           "AND u.name NOT IN ( :not_in__u_name_0 ) "
# params == {"in__status_0": "on", "not_in__u_name_0": "bob"}

Node: Declarative SQL decorators for selects, exists checks, and updates

Functional constraints

  • Wrapped functions are query suppliers: return exactly one QueryData (or yield several, generators under sqlupdate only). Other payloads raise QueryDataError.
  • Decorator syntax: only the called form executes (@sqlquery(...), @sqlexists(...), @sqlupdate(...)). Each factory unconditionally returns its inner decorator, so bare usage binds the name to the unapplied closure; calling it never runs SQL — positional args bind to func and return the inner wrapper, otherwise TypeError.
  • sqlquery: connection-only, no transaction; mapper=None → RecordCombiningMapper, which merges records with equal key-column values (default ['id']) into one DbMapResult and falls back to one result per row when a key column is missing from the records; mapper classes are instantiated per call; map_records output is returned as-is.
  • DbMapResult: constructor ensures an 'id' key defaulting to None; raw() drops 'id' when None; has(field) is true only for non-None values; get(field, default) falls back only on missing keys, not None values.
  • sqlexists: rewrites SELECT EXISTS … → SELECT 1 WHERE EXISTS …, otherwise wraps as SELECT 1 WHERE EXISTS ( … ); returns scalar() == 1, always a bool, never raises for absent rows.
  • sqlupdate: begin → statements → commit, or rollback + propagate. disable_foreign_key_checks sets FOREIGN_KEY_CHECKS=0 before and =1 after statements, inside the transaction. get_last_insert_id is injected only when the function signature names it, and removed before on_success. Generator yields execute sequentially pre-commit; list query_params fan out to one execute per dict there, but raise Exception (Params must not be a list) in non-generator updates.
  • All three default to isolation_level=READ_COMMITTED, applied via execution_options before any transaction begins.

Example (multi-statement transactional update):

from dysql import QueryData, sqlupdate

@sqlupdate()
def create_order(item, get_last_insert_id=None):
    yield QueryData("INSERT INTO orders(value) VALUES (:value)", item)
    order_id = get_last_insert_id()
    yield QueryData(
        "INSERT INTO order_items(order_id, value) VALUES (:order_id, :value)",
        {"order_id": order_id, "value": item["value"]},
    )

create_order({"value": "x"})  # both inserts commit atomically

Node: Query result mapping to Python objects

Functional constraints

  • All mappers implement BaseMapper.map_records(records: sqlalchemy.engine.CursorResult) -> Any; custom strategies subclass it. Custom record classes satisfy DbMapResultBase (map_record, raw, has, get) and may override the create_instance / get_key_columns hooks.
  • RecordCombiningMapper groups by hash(tuple(record[c] for c in get_key_columns())) (default key ["id"]); the if lookup: test evaluates the combined hash, so falsy key values (e.g. id=0) still combine — the positional-entry branch fires only when a key column is missing, the key list is empty, or the combined hash is itself falsy. Repeated map_record calls overwrite columns — last row per key wins; no list accumulation.
  • record_mapper=None on RecordCombiningMapper/SingleRowMapper bypasses mapping (cursor / first raw row returned).
  • Empty inputs: [] / None / [] / None / {} for combining, single-row, single-column, single-row-column, key-value respectively — except that KeyValueMapper in multi-value mode returns an empty defaultdict(list) instead of a plain {}.
  • KeyValueMapper addresses columns positionally by int; key_column == value_column raises MapperError at construction; multi-value mode returns defaultdict(list).
  • DbMapResult replaces any falsy id with None (a selected id of 0 or '' is overwritten); has() is None-sensitive; raw() deletes id whenever its value is None — real NULL id columns included — and recurses into nested result objects.
  • Mapper instances hold no per-call state; reuse/sharing is safe.

Example

from dysql import sqlquery, QueryData, DbMapResult, RecordCombiningMapper, KeyValueMapper

class User(DbMapResult):
    @classmethod
    def get_key_columns(cls):        # composite key: rows group on both columns
        return ["id", "org_id"]

@sqlquery(
    QueryData("SELECT u.id, u.org_id, u.name, p.perm FROM users u "
              "JOIN perms p ON p.user_id = u.id WHERE u.org_id = :org"),
    mapper=RecordCombiningMapper(User),
)
def load_users(org: int): ...

users = load_users(7)                # list[User], one per (id, org_id)
lookup = KeyValueMapper(0, 1, has_multiple_values_per_key=True)
# keyed defaultdict(list) of column-1 values grouped by column-0

Node: Pydantic model result mapping

Functional constraints

  • Subclass DbMapResultModel; plain annotated fields bind columns directly.
  • Metadata class attributes route aggregation: _list_fields, _set_fields (scalar per row), _csv_list_fields (split on ",", strip, TypeAdapter.validate_python against the annotation each record), _json_fields (TypeAdapter.validate_json only while _has_been_mapped() is false; later records' JSON columns are ignored entirely — no validation, no aggregation), _dict_key_fields (DB→model) paired with the inverse _dict_value_mappings (model→DB value column; those columns are popped after every row, dict mapping executed or not).
  • create_instance() uses model_construct: no validation at construction.
  • First map_record validates via __init__ (type coercion applies); subsequent calls mutate __dict__ with no validation — only CSV elements are validated on every record; JSON documents are validated only on the record that seeds the field.
  • Null rules: list/set/dict skip only None (dict checks only the value column, never the key column, so None keys can surface); CSV and JSON skip any falsy value (CSV's check precedes str() coercion). Collection fields need defaults or first-record validation fails.
  • CSV aggregation never dedupes; an empty CSV string leaves the default in place (None for Optional, [] for defaulted lists).
  • _map_dict performs unguarded _dict_value_mappings and Row lookups, so wiring mismatches (missing model-name entry, or value column absent from the record) raise KeyError on any row containing the key column.
  • Composite identity keys: override get_key_columns() returning all key column names; grouping is the mapper's job, not the model's.
  • raw() == model_dump(); has(field) checks __dict__; get(field, default) is a plain dict read.

Example

from typing import Any, Dict, List, Optional, Set
from dysql.pydantic_mappers import DbMapResultModel

class UserRolesModel(DbMapResultModel):
    _csv_list_fields: Set[str] = {"emails"}          # "a@x,b@x" -> list
    _list_fields: Set[str] = {"role"}                # one value per row -> list
    _dict_key_fields: Dict[str, str] = {"attr_key": "attrs"}
    _dict_value_mappings: Dict[str, str] = {"attrs": "attr_value"}
    id: int
    emails: Optional[List[str]] = None               # collections need defaults
    role: List[str] = []
    attrs: Dict[str, Any] = {}

models = RecordCombiningMapper(record_mapper=UserRolesModel).map_records(rows)
models[0].raw()  # {'id': 7, 'emails': ['a@x', 'b@x'], 'role': ['r1', 'r2'], 'attrs': {'k': 'v'}}

Node: Integration test database management

Implementation nodes

  • Context manager only: __enter__ provisions, __exit__ tears down; the constructor records config and detects docker (/.dockerenv, or docker/kubepod/lxc in /proc/1/cgroup) with no I/O.
  • __enter__ order: DROP DATABASE IF EXISTS → CREATE DATABASE IF NOT EXISTS → optional mariadb-dump --no-data --routines {schema_db_name} | mariadb {db_name} → set_default_connection_parameters(host, username, password, db_name, **connection_defaults) → set_current_database(db_name) → poll table counts every 0.25 s until schema-source and test-database counts match.
  • Schema copy is structure plus routines only; data rows are never duplicated.
  • MariaDbTestManager fixes the forwarded connection defaults to port=3306, pool_size=3, charset="utf8", echo_queries; the base forwards unknown kwargs into set_default_connection_parameters (valid keys: database_key, pool_recycle, collation, ...).
  • Connection defaults merge, not replace: the process-global registry (_DEFAULT_CONNECTION_PARAMS_BY_KEY) is updated via update(locals()), so re-entering with the same db_name reuses the existing entry — only re-supplied parameters change, and stale optional parameters from prior entries persist for the process lifetime.
  • Any forwarded database_key must equal db_name: set_current_database(db_name) resolves under db_name, while a divergent key registers under a different registry entry, so the first decorated query raises DBNotPreparedError ("No connection parameters found for database key ''") rather than failing at provisioning.
  • is_set_current_database_supported() is a deprecated shim that always returns True; set_current_database(db_name) is invoked unconditionally in __enter__, with no skip path.
  • Env fallbacks: MARIA_HOST=localhost, MARIA_USERNAME=root, MARIA_PASSWORD=password, MARIA_CONTAINER_NAME=mariadb.
  • Not-in-docker ⇒ commands wrapped in docker exec {docker_container} bash -c '...'; in-docker ⇒ run directly. Commands use timeout=30, check=True → CalledProcessError aborts setup.
  • keep_db=True skips the teardown DROP DATABASE IF EXISTS for debugging.
  • _get_tables_count is itself a @sqlquery(mapper=CountMapper()) over information_schema.TABLES; the readiness poll loops forever on mismatch (no timeout).
  • Import contract: the manager runs from dysql import set_default_connection_parameters, databases — set_default_connection_parameters must stay importable from dysql, and the dysql.databases module must stay importable; databases.set_current_database and databases.is_set_current_database_supported are accessed as module attributes.

Example (module-scoped autouse fixture):

@pytest.fixture(scope="module", autouse=True)
def setup_db(self):
    with MariaDbTestManager(
        f"testdb_{self.__class__.__name__.lower()}",
        schema_db_name="appdb",   # duplicate schema only (--no-data --routines)
        keep_db=False,            # True retains the DB after the run
    ):
        yield  # __exit__ drops the test database unless keep_db