Download tasks/data/forward/adobe__dy-sql.0ebb317/instruction.md from Lego-X/ProgramGen: direct link, hf CLI and curl.
- Browser
- Download file 98.7 kB
-
https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/adobe__dy-sql.0ebb317/instruction.md
- Command line
-
hf download hf://datasets/Lego-X/ProgramGen/tasks/data/forward/adobe__dy-sql.0ebb317/instruction.md
-
curl -L -o instruction.md https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/adobe__dy-sql.0ebb317/instruction.md
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:
Do NOT create or modify any files under the test directories (e.g.
tests/,test/,testing/, or files namedtest_*.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.Your package MUST be importable by the name the tests use. The hidden tests
importyour package by its documented top-level name (see the Project Directory Structure and API Usage Guide below). Provide a validpyproject.toml/setup.py/setup.cfgand lay out your modules so thatpip install -e .succeeds and the package imports cleanly. If your package is not installable/importable, every test errors out and the reward is 0.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/repoat 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
- Optionally register
set_database_init_hook(hook)first. The hook is stored as a class attribute onDatabase, 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. - Call
set_default_connection_parameters. The four required values (host,user,password,database) are falsy-checked; a failure raisesDBNotPreparedErrorimmediately, before any state is stored. On success the whole parameter set is merged into_DEFAULT_CONNECTION_PARAMS_BY_KEY[database_key](database_keydefaults to thedatabasename when falsy). - Execute a decorated function. The container resolves the current key — the
set_current_databasecontextvar value when non-empty, otherwise the first key inserted into_DEFAULT_CONNECTION_PARAMS_BY_KEY— and returns theDatabasefor that key, creating and caching it on first request. Database.engine(first access only) reads the stored params, buildsmysql+mysqlconnector://user:password@host:port/database?charset=charset[&collation=collation]viasqlalchemy.create_engine(..., pool_size=..., pool_recycle=..., echo=echo_queries, pool_pre_ping=True), then invokes the hook ashook(database_name, engine)— the storeddatabasename, not the key (they coincide for single-tenant setups).- Engine construction opens no connection:
create_engineonly constructs the pool andpool_pre_pingpings 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_KEYis adefaultdict(dict); re-calling with the same key merges (dict.updateover the fulllocals()snapshot, which includes the resolveddatabase_key). Becauselocals()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 withecho_queries=Truefollowed by a re-call that omitsecho_queriesstoresecho_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(adictsubclass) caches oneDatabaseper key on__getitem__;DatabaseContainerSingleton.__new__returns the same instance for every construction, anddysql.connectionsinstantiates it at import time.- Each
Databasecaches_engineafter 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 andNoneboth 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 whenset_current_databasenames a key never configured, or after the params dict is cleared while aDatabaseobject 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, whileDatabaseobjects 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-levelContextVar(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()isset_current_database("")and only resets the calling context.is_set_current_database_supported()is deprecated and always returnsTrue.- Only the four required values are validated; e.g.
pool_size=0passes straight through tocreate_engine. - The hook applies to all keys built after registration, and engines echo queries only when
echo_queries=Truewas 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 returnsTrue; older code guarded usage behind it, and it remains safe to call.DatabaseContainerSingletonis a singleton dict that materializes aDatabaseinstance for any requested key once parameters are registered. Itscurrent_databaseproperty 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 thedefaultdict). 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 toDatabase.set_init_hook) registers a single class-level hook shared by everyDatabaseinstance: one global hook across all keys, and a later registration replaces it globally. It fires exactly once per engine creation, ashook(database_name, engine), wheredatabase_nameis thedatabasevalue from the connection parameters registered under the resolved key — not the context-selected tenant key; whendatabase_keydiffers from the database name, the hook observes the latter (a test-sensitive distinction). - Inside
dysql.connections,_ConnectionManagerreads_DATABASE_CONTAINER.current_database.engineat decorated-function invocation time. That engine is cached per key on first use, and the hook fires only at that lazy creation.
Realistic workflow
- 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". Omittingdatabase_keyregisters the database name as the key. - In the request coroutine, call
set_current_database("tenant_b")before invoking decorated functions; callreset_current_database()when done (or rely on context isolation). - Every
@sqlquery/@sqlupdate/@sqlexistscall 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_parametersmust run before any decorated call resolves its database. With zero registered parameter sets, the failure is eager:DatabaseContainer.__getitem__(and thereforecurrent_database) raisesDBNotPreparedErrorwithUnable to connect to a database, set_default_connection_parameters must first be calledduring key resolution itself — noDatabaseobject is created and.engineis never reached. With parameters registered but the selected key missing, the container does return aDatabaseobject and the failure is lazy: itsengineproperty raisesDBNotPreparedErrorwithNo 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 betweenset_current_databaseand 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 exactlyset_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
Databaseentries 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-registeringset_default_connection_parametersfor 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()returningTruealways 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
DBNotPreparedErrormessage above — not atset_current_databasetime, 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_databasewith
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
- Type gate. Anything that is not a
QueryDatainstance raisesQueryDataError("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. - 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-Noneentry intemplate_params; the first missing key in left-to-right order aborts withListTemplateException("Missing template keys ['<key>']")— a query with several missing templates reports only the first one. An explicitNonetemplate value counts as missing, and an absent entry is indistinguishable from it. - 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}ANDrenders asWHERE 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 writeWHERE {in__status}, neverWHERE status {in__status}. - Param merge.
query_paramsare copied in first, then each template's generated params are applied in placeholder order, so template keys win collisions withquery_params.
Template semantics
in__:col IN ( :key_0, :key_1, ... ). An empty list degrades to the predicate1 <> 1with no params added (matches nothing).not_in__: same shape withNOT IN; an empty list becomes1 = 1with no params (matches everything).values__:VALUES ( :key_0_0, :key_0_1, ... ), ( :key_1_0, ... )for bulk inserts. Failing values split into two cases: aNone(or absent)template_paramsentry never reaches the generator — it is caught by the step-2 missing-key check and raisesListTemplateException("Missing template keys ['values__<key>']"). Only a falsy-but-non-Nonevalue (empty list/tuple/set/str,0) passes validation and reachesTemplateGenerators.values, which raisesListTemplateExceptionwith "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 afterIN—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 getkey_<row>_<col>; a scalar row gets the single-level namekey_<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-levelkey_<i>params, passing any tuple through as a raw param value (e.g.[1, (2,3)]yieldsin__k_0=1,in__k_1=(2,3)). - Row detection keys off the effective key starting with
values, so a directvalues('actors', [[1,2]])call flattens rows to single-levelactors_<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_paramsgiven as a list of dicts makes the decorator issue one query per entry;template_paramsexists precisely to keep it a single statement.- Duplicate placeholders in one query are all replaced (string
replacehits 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_datasplits each validated key on__and unpacks exactly two parts, so such keys — even withtemplate_paramscorrectly supplied — surface as an unpackingValueError("too many values to unpack") fromget_query_data, not aListTemplateException. TemplateGeneratorsis also usable standalone to build fragments by hand;get_templatedispatches onlyin,not_in, andvalues, returningNonefor anything else (the regex-driven path can never hit that).get_query_datais exactly what the decorators invoke, so unit tests can exercise template expansion without a database by calling it directly on a hand-builtQueryData.
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:
- Acquires a fresh connection from the current database container's engine and applies
isolation_level(defaultREAD_COMMITTED) throughexecution_options— before any transaction begins. - Calls the wrapped function with the caller's arguments. The function is a query supplier: it must return (or, for
sqlupdategenerators, yield) aQueryData. Any other payload — including the raw tuple shown in some docstring examples — raisesQueryDataErrorwith messageSQL annotated methods must return an instance of QueryData for query information. - Normalizes the payload with
get_query_data: list templates ({in__col},{not_in__col},{values__x}) are validated againsttemplate_params(missing or empty →ListTemplateException), expanded in place, and their generated bind parameters merged into the query params. - Executes through
sqlalchemy.texton that connection. Falsy params become{}; aDbMapResultpassed as params is converted with.raw(). - Restores state on context exit:
sqlquery/sqlexistssimply close the connection;sqlupdatecommits 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.
mappermay be aBaseMappersubclass (instantiated fresh per call) or an already-built instance;Nonedefaults toRecordCombiningMapper. The wrapper returnsmapper.map_records(records)directly, so the return type follows the mapper: list ofDbMapResultrows for the default, scalars forSingleColumnMapper, first row forSingleRowMapper, first scalar forCountMapper(SingleRowAndColumnMapper;Nonewhen the result set is empty, not 0), dicts forKeyValueMapper.- Default-mapper merging:
RecordCombiningMappercollapses records sharing the key columns (default['id']fromDbMapResultBase.get_key_columns) into oneDbMapResult, 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
MapperErrorfrom the mapper layer.
DbMapResult value semantics
- The constructor always ensures an
'id'key, defaulting toNone. raw()deletes the'id'entry when its value isNone, so a row without an id serializes without that key — including when aDbMapResultis passed as query params.has(field)is true only when the stored value is notNone: an explicitly-Nonefield counts as absent.get(field, default)returns the default only when the key is missing, not when the value isNone.
@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 EXISTSbecomesSELECT 1 WHERE EXISTS ...; anything not starting withSELECT 1 WHERE EXISTSis wrapped asSELECT 1 WHERE EXISTS ( <query> ). A query that already begins withSELECT 1 WHERE EXISTSpasses through untouched. - The rewritten statement runs with
.scalar()and the decorator returnsresult == 1— a strict Python bool. No matching row yieldsNULL→None→False; a value other than 1 also yieldsFalse. Missing rows never raise.
@sqlupdate(...)
- Opens an explicit transaction before executing. Clean exit commits; any exception logs the error, rolls back, and propagates —
on_successis 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_idis injected only if the wrapped function's signature declares a parameter with that exact name. The decorator supplies a lambda that executesSELECT LAST_INSERT_ID()and returns its scalar; the kwarg is removed beforeon_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_paramsis a list, the same query executes once per dict — useful for batch child rows. In non-generator updates, a listquery_paramsraisesExceptionwith messageParams must not be a list. - Typical generator shape: declare
def fn(data, get_last_insert_id=None), yield the parent insert, callget_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_parametersbeforehand). - Template placeholders are matched by exact key; a
template_paramsentry that is present butNonecounts as missing and raisesListTemplateException. sqlquerymapping consumes the whole cursor; pick the mapper to match the query shape.sqlexistsdocstrings show bare@sqlexistsdecoration and bare string/tuple payloads, but neither works as shown: use the called decorator form and always supplyQueryData.
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
idvalue is replaced withNone. Every instance therefore gets anidattribute defaulting toNone, and this applies even when the query did selectid— a genuinely selected id of0or''is overwritten withNone. - Dict-style access: subscript reads go through
dict.get, soresult["missing"]silently returnsNoneinstead of raisingKeyError; only assignment writes through to__dict__.str(result)prints that dict. map_recordcopies 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 SQLNULLreportshas(...) == False.get(field, default)is a plain dict lookup with default.raw()recurses: nestedDbMapResultBasevalues (including inside lists) are unwrapped to dicts. It deletes theidkey whenever its value isNone— so besides the synthetic placeholder, a real id column that came back as SQLNULLis 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 byhash(tuple(record[c] for c in get_key_columns()))into anOrderedDict, so first-appearance order is preserved. A row is not combined when any key column is missing from it or whenget_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;Noneon an empty result;record_mapper=Nonereturns 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, elseNone.CountMapperis an unchanged subclass: use it forSELECT COUNT(*)to get a scalar (orNoneon empty).KeyValueMapper(key_column=0, value_column=1, has_multiple_values_per_key=False)— dict keyed by positional column index (integers, not names). Construction validateskey_column != value_columnand raisesMapperErrorimmediately, so a bad configuration fails before any query runs. In default mode duplicate keys overwrite (last row per key wins); withhas_multiple_values_per_key=Trueit returns adefaultdict(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
- 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 viaTypeAdapter, then extended into the list._json_fields: the column holds a JSON document; parsed viaTypeAdapter(annotation).validate_json, but only while the instance is not yet in merge mode (see validation timing below)._dict_key_fieldsmaps DB column name → model dict field;_dict_value_mappingsis 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.
- Instantiate via the mapper.
create_instance()builds the object withmodel_construct, so creation itself never validates — validation is deferred. - Merge rows. The mapper calls
map_record(record)once per row. The first call collects the row into a dict and runs it throughself.__init__, so full pydantic validation and coercion execute exactly once (e.g.field_bool: 1becomesTrue). Every later call mutates__dict__directly — no revalidation — extending/appending/adding into the existing collections.
State and ordering
_has_been_mapped()isbool(model_fields_set): anything set by the first__init__flips the instance into merge mode. This is whycreate_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_mappingsis popped unconditionally, so value columns never leak into the output even when no dict mapping ran. - Row grouping is the mapper's responsibility:
SingleRowMappertakes only the first record;RecordCombiningMapperre-invokesmap_recordfor every row sharing the identity key. The key defaults to columnid; overrideget_key_columns()(e.g.return ["a", "b"]) for composite keys — grouping hashes the full key tuple, soa=1,b=testanda=1,b=othertestare 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 onlyNonevalues — falsy non-Nonevalues (0,False,"") are appended/added normally. The dict path checks only the value column; the key column is never checked, so aNonekey with a non-Nonevalue still yields a{None: value}entry. CSV and JSON skip any falsy value, and CSV's falsy check precedes thestr()coercion (numeric0/FalseCSV 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. AnOptional[List[str]] = Nonefield staysNoneon 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. ANonein the first record followed by data later still aggregates in row order. - Validation timing: CSV elements are validated on every record (via
TypeAdapter.validate_pythonagainst the field annotation), so a bad element in any later row raisesValidationErroreven though merging itself skips validation. JSON differs:TypeAdapter.validate_jsonruns 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()returnsmodel_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__
- Destructive re-create.
DROP DATABASE IF EXISTS {db_name}followed byCREATE DATABASE IF NOT EXISTS {db_name}, run through themariadbCLI.db_nameis caller-supplied, not unique per run — re-entering with the same name wipes any prior database, which is exactly what makes reruns deterministic. - Schema duplication. If
schema_db_nameis set, a single shell pipelinemariadb-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. - Connection defaults.
set_default_connection_parameters(host, username, password, db_name, **connection_defaults)registers the test database. ForMariaDbTestManagerthe forwarded defaults are fixed toport=3306,pool_size=3(the library default is 10),charset="utf8", andecho_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 samedb_namereuses the existing registry entry — only re-supplied parameters change, while stale optional parameters from prior entries (collation,pool_recycle, a previously supplieddatabase_key) silently survive into the new entry. - Current-database selection.
is_set_current_database_supported()is a deprecated backwards-compatibility shim that always returns True, soset_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/@sqlexistscalls resolve to the test database with no extra configuration. Because resolution happens underdb_name, any forwardeddatabase_keymust equaldb_name: a divergent key registers the defaults under a different registry entry, so the first decorated query raisesDBNotPreparedError("No connection parameters found for database key ''") instead of failing at provisioning. - Readiness wait. With a
schema_db_name,_wait_for_tables_existpolls every 0.25 s until theinformation_schema.TABLEScount 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=Trueretains the database:__exit__skips theDROP DATABASE IF EXISTSteardown 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_parametersis imported from thedysqlpackage, whiledatabases.set_current_database(...)anddatabases.is_set_current_database_supported()are reached as attributes of the importeddatabasesmodule object (thedysql.databasessubmodule). What must remain importable when the test-manager module is collected is thedysql.databasesmodule, plusset_default_connection_parametersremaining importable fromdysql.
Test-sensitive behavior
- The constructor performs no I/O; all side effects occur on
__enter__. - Entering twice in one process with the same
db_namerecreates and wipes the database; since defaults merge rather than replace, stale optional parameters from the earlier entry remain in effect. - A forwarded
database_keydiffering fromdb_namesurfaces asDBNotPreparedErrorat 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
DBNotPreparedErrorrather 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-dumpandmariadbmust be resolvable there (inside the container when wrapped). - Empty required connection values raise
DBNotPreparedErrorfrom 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): raisesDBNotPreparedErrorif any required value is falsy (messageDatabase parameter "{name}" is not set or empty and is required); otherwise mergeslocals()into_DEFAULT_CONNECTION_PARAMS_BY_KEY[database_key or database]. Becauselocals()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 thatQueryDatamay override at execution time.- Engine build is lazy, once per
Database, and opens no connection: URLmysql+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 ashook(database_name, engine)(name, not key), only for engines built afterset_database_init_hookwas called.pool_pre_pingapplies 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 cachesDatabase(key);current_databaseuses the contextvar key (module-levelContextVar, context-local and inherited by context copies), else the first-registered key;DatabaseContainerSingletonyields one shared instance; params lookup is.get(key, {})and never mutates the defaultdict;pool_pre_pingis 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_VARis acontextvars.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()callsset_current_database("").is_set_current_database_supported()always returnsTrue(deprecated shim).- Effective key resolution (
DatabaseContainer.current_databasevia_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__raisesDBNotPreparedError("Unable to connect to a database, set_default_connection_parameters must first be called")eagerly, during resolution, when no parameter sets are registered — noDatabaseinstance is produced and.engineis never reached. With parameters registered but the key absent,__getitem__materializes and caches aDatabasewhoseengineproperty raisesDBNotPreparedError(f"No connection parameters found for database key '{self.database}'")at first engine access. - Init hook:
set_database_init_hookdelegates to the classmethodDatabase.set_init_hook, which stores the hook as a class attribute — one global hook shared by everyDatabaseinstance, and re-registration replaces it for all keys. It fires once per engine creation ashook(database_name, engine), wheredatabase_nameis thedatabasename from the parameters registered under the resolved key, not the context-selected key. - Engines are lazy and cached on the per-key
Databaseinstance; 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_datarequires aQueryDatainstance; any other return value from an annotated function raisesQueryDataError.- Every
{in__…}/{not_in__…}/{values__…}token needs a non-Nonetemplate_paramsentry; the first missing key (left to right) raisesListTemplateException("Missing template keys …").Noneand absent entries are both treated as missing; only falsy-but-non-Nonevalues reach the generator. in__/not_in__with an empty list emit1 <> 1/1 = 1with no params;values__with an empty or otherwise falsy non-Nonevalue raisesListTemplateExceptionfrom 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-tuplein__/not_in__values and list/tuple/setvalues__rows use two-levelkey_<row>_<col>; scalarvalues__rows use single-levelkey_<row>; mixedin__/not_in__lists fall back to flatkey_<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_paramsmerge first; template params override on key collision. Neither input dict is mutated.- Direct
TemplateGeneratorscalls (nolegacy_key) name params from the bare column name; a barestrvalue 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 unpackingValueErrorwhenget_query_datasplits 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 undersqlupdateonly). Other payloads raiseQueryDataError. - 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 tofuncand return the inner wrapper, otherwiseTypeError. sqlquery: connection-only, no transaction;mapper=None→RecordCombiningMapper, which merges records with equal key-column values (default['id']) into oneDbMapResultand falls back to one result per row when a key column is missing from the records; mapper classes are instantiated per call;map_recordsoutput is returned as-is.DbMapResult: constructor ensures an'id'key defaulting toNone;raw()drops'id'whenNone;has(field)is true only for non-Nonevalues;get(field, default)falls back only on missing keys, notNonevalues.sqlexists: rewritesSELECT EXISTS …→SELECT 1 WHERE EXISTS …, otherwise wraps asSELECT 1 WHERE EXISTS ( … ); returnsscalar() == 1, always a bool, never raises for absent rows.sqlupdate: begin → statements → commit, or rollback + propagate.disable_foreign_key_checkssetsFOREIGN_KEY_CHECKS=0before and=1after statements, inside the transaction.get_last_insert_idis injected only when the function signature names it, and removed beforeon_success. Generator yields execute sequentially pre-commit; listquery_paramsfan out to one execute per dict there, but raiseException(Params must not be a list) in non-generator updates.- All three default to
isolation_level=READ_COMMITTED, applied viaexecution_optionsbefore 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 satisfyDbMapResultBase(map_record,raw,has,get) and may override thecreate_instance/get_key_columnshooks. RecordCombiningMappergroups byhash(tuple(record[c] for c in get_key_columns()))(default key["id"]); theif 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. Repeatedmap_recordcalls overwrite columns — last row per key wins; no list accumulation.record_mapper=NoneonRecordCombiningMapper/SingleRowMapperbypasses mapping (cursor / first raw row returned).- Empty inputs:
[]/None/[]/None/{}for combining, single-row, single-column, single-row-column, key-value respectively — except thatKeyValueMapperin multi-value mode returns an emptydefaultdict(list)instead of a plain{}. KeyValueMapperaddresses columns positionally by int;key_column == value_columnraisesMapperErrorat construction; multi-value mode returnsdefaultdict(list).DbMapResultreplaces any falsyidwithNone(a selected id of0or''is overwritten);has()is None-sensitive;raw()deletesidwhenever its value isNone— 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_pythonagainst the annotation each record),_json_fields(TypeAdapter.validate_jsononly 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()usesmodel_construct: no validation at construction.- First
map_recordvalidates 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, soNonekeys can surface); CSV and JSON skip any falsy value (CSV's check precedesstr()coercion). Collection fields need defaults or first-record validation fails. - CSV aggregation never dedupes; an empty CSV string leaves the default in place (
NoneforOptional,[]for defaulted lists). _map_dictperforms unguarded_dict_value_mappingsand Row lookups, so wiring mismatches (missing model-name entry, or value column absent from the record) raiseKeyErroron 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, ordocker/kubepod/lxcin/proc/1/cgroup) with no I/O. __enter__order: DROP DATABASE IF EXISTS → CREATE DATABASE IF NOT EXISTS → optionalmariadb-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.
MariaDbTestManagerfixes the forwarded connection defaults toport=3306,pool_size=3,charset="utf8",echo_queries; the base forwards unknown kwargs intoset_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 viaupdate(locals()), so re-entering with the samedb_namereuses the existing entry — only re-supplied parameters change, and stale optional parameters from prior entries persist for the process lifetime. - Any forwarded
database_keymust equaldb_name:set_current_database(db_name)resolves underdb_name, while a divergent key registers under a different registry entry, so the first decorated query raisesDBNotPreparedError("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 usetimeout=30,check=True→CalledProcessErroraborts setup. keep_db=Trueskips the teardownDROP DATABASE IF EXISTSfor debugging._get_tables_countis itself a@sqlquery(mapper=CountMapper())overinformation_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_parametersmust stay importable fromdysql, and thedysql.databasesmodule must stay importable;databases.set_current_databaseanddatabases.is_set_current_database_supportedare 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