- Packaging: The PostgreSQL driver is now an optional dependency exposed via extras instead of a hard
install_requirespin. Install withrick-db[pgsql](buildspsycopg2from source) orrick-db[pgsql-binary](prebuiltpsycopg2-binarywheel) — both satisfy thepsycopg2import. Dev tooling bumped:pytest9.1.1,coverage7.14.3,tox4.56.1,clickhouse-connect>=1.3.0.
- Testing: Replaced the
tox-dockersetup with testcontainers. The PostgreSQL and ClickHouse containers used by the integration tests are now started and stopped fromtests/conftest.py(session-scoped fixtures), so the suite can be run with a plainpytestinvocation and no longer depends ontoxor environment-variable wiring. Removed the[docker:*]sections fromtox.iniand swappedtox-dockerfortestcontainers[postgres]inrequirements-dev.txt.
- Added a
CIGitHub Actions workflow (test matrix on Python 3.10–3.14, flake8/black lint, build,pip-audit+banditsecurity scan, gated by aci-successjob), replacingrun-tests.yml. - Reworked the SBOM workflow to generate CycloneDX + SPDX SBOMs, scan them with Grype, sign them with Cosign, and upload them to the release (with optional Dependency-Track submission).
- sql/dialect.py, sql/common.py: Fixed SQL injection in JSON path handling. The
pathargument ofjson_extract(),json_extract_text(),json_contains_path(),json_path_query()and the correspondingJsonField/PgJsonFieldhelpers was interpolated into the generated SQL wrapped in single quotes without escaping embedded quotes. A JSON path sourced from untrusted input could break out of the string literal and inject arbitrary SQL. Embedded single quotes are now escaped (doubled) via a newSqlDialect._quote_str()helper across all dialects (PostgreSQL, MySQL, ClickHouse, SQLite, default). Note: JSON paths are still interpolated, not parameterized — callers should continue to treat them as code, not data.
- sql/common.py:
PgJsonField.__getitem__(square-bracket key access) now emits a single-quoted, quote-escaped JSON key (data->'name') instead of a double-quoted one (data->"name"). The previous form was parsed by PostgreSQL as an identifier reference rather than a JSON key (a correctness bug) and did not escape the key. - cli/commands/dto.py: The
dtocode generator interpolated database-derived table, schema, and column names into single-quoted Python string literals without escaping. A maliciously named database object could inject code into the generated DTO module. Identifier string values are now emitted viarepr(), and attribute names are validated as Python identifiers (raising an error otherwise) before being written.
- Dependencies bumped to latest releases:
psycopg2/psycopg2-binary2.9.12,toml0.10.2,setuptools82.0.1,clickhouse-connect>=1.1.1, and dev tooling (pytest9.0.3,pytest-cov7.1.0,coverage7.14.1,tox4.55.0,mkdocs-material9.7.6,mdx-include1.4.2).
- docs/json_operations.md: Added a security warning clarifying that JSON paths are interpolated (not parameterized) and must not be built from untrusted input, and corrected the no-dialect
JsonField['name']example output. - docs/classes/pgjsonfield.md, docs/json_operations.md: Updated
PgJsonField->examples to use single-quoted JSON keys (data->'name') to match the corrected operator output.
ClickHouseConnectionPool— thread-safe connection pool for ClickHouse, with configurableminconn/maxconn, connection health checks viaping, stale connection recovery, custom connection factory support, and profiler passthroughClickHouseManagernow accepts bothClickHouseConnectionandClickHouseConnectionPool, with optionaldatabaseparameter override- Integration and concurrency tests for
ClickHouseConnectionPool - Pool-based
ClickHouseManagerintegration tests
- Cache SQL identifier quoting (
_qi()) with@lru_cacheacross all dialects, eliminating redundant string work on repeated field/table references - Replace
.format()string building with f-strings throughout query builders (select.py,insert.py,update.py,delete.py,dialect.py,common.py) - Replace
list(dict.items()).pop()anti-pattern withnext(iter(dict.items()))inSelect._where(),having(),_join(),_parse_table_def() - Remove unnecessary
.keys()calls from dict membership tests inSelectandBaseRecord - Single-pass
_render_from()replaces three separate classification loops plus three rendering loops - Use
isinstance()instead oftype() in [list, tuple]checks inSelect - Cache
Fn.count()singleton for the common no-argCOUNT(*)case - Optimize
BaseRecord.asrecord()to use dict comprehension instead of copy-and-pop loop - Simplify
BaseRecord.__getattribute__()to usedict.get()instead ofin .keys()+ lookup - Replace
_valid_joins/_valid_unions/_valid_orderlists withfrozensetfor O(1) membership checks - Remove redundant
.strip()fromSelect.assemble()by filtering empty parts and fixing root cause in_render_order() - Use
.extend()instead of per-element.append()loops for value list copying
- Fixed ClickHouse docker image tag in
tox.inifrom non-existent25.8to25.6 - Breaking: ClickHouse migrations no longer support multiple SQL statements per file. The previous semicolon-based splitting was unreliable (broke on semicolons inside string literals). Each migration file must now contain a single SQL statement.
- profiler/profilers.py:
NullProfiler.get_events()now returns an emptyEventCollectioninstead ofNone, preventingTypeErrorwhen iterating over profiler events on unprofiled connections - migrations.py:
BaseMigrationManager.repositoryproperty now caches the repository instance instead of creating a new one on every access, eliminating redundant object creation and enabling query cache reuse - sqlite/migrations.py: Replaced naive
content.split(";")with a string-aware statement splitter that respects single-quoted strings, preventing breakage on SQL containing semicolons in string literals
- connection.py: Replaced mutable default argument
profiler=NullProfiler()withNonesentinel pattern to avoid sharing a single profiler instance across all connections - repository.py: Fixed
type() not in [list, tuple]checks to useisinstance()inupdate_where()andcount_where()for proper subclass support - repository.py: Removed redundant
.keys()call fromself.pk in data.keys()inupdate() - mapper.py:
BaseRecord.add()now copies_fieldmapon first write to avoid mutating the class-level dict shared across all instances - profiler/profilers.py:
DefaultProfileris now thread-safe —add_event(),clear(), andget_events()are protected by a lock;get_events()returns a snapshot copy
- cache.py: Removed redundant
.keys()calls inQueryCache.get()andhas() - dbgrid.py: Removed redundant
.keys()call in search type validation - insert.py:
Insert.values()now storeslist(values.keys())instead of adict_keysview that could change if the source dict is mutated - cli/config.py:
type(config[k]) is dictreplaced withisinstance()for compatibility with dict subclasses from TOML parsers - cli/config.py: Password file reader now strips trailing newline/carriage return to prevent authentication failures
- cli/manage.py: Replaced
p.name.rsplit(".py")[0]withp.stemto correctly extract module names from filenames containing.pyelsewhere - select.py: Removed redundant
operator is not Nonecheck inside theelsebranch of_where()whereoperatoris guaranteed non-None - select.py: Changed
str(cols) == "*"wildcard check tocols == "*"to avoid false negatives whencolsis a list
- mapper.py:
type(data) is not dictreplaced withnot isinstance(data, dict)in__setattr__for proper dict subclass handling - sql/common.py:
JsonField.__getitem__now uses dialect-aware JSON extraction instead of hardcoded PostgreSQL->>operator; falls back toJSON_EXTRACT()without a dialect - cli/commands/dto.py: Generated class names are now sanitized — non-alphanumeric characters are stripped and names starting with digits are prefixed with
T - pool.py: Fixed race condition in stale connection recovery where releasing the
_usedslot before creating the replacement could allow another thread to exceedmaxconn - clickhouse/repository.py: Fixed
type() not in [list, tuple]checks to useisinstance(); removed redundant.keys()call - clickhouse_example.py: Fixed
f.field_typereference tof.type(attribute does not exist onFieldRecord)
Fnhelper class for common SQL functions in the query builder, returningLiteralinstances for use in column definitions- Aggregate:
count,sum,avg,min,max - Math:
abs,ceil,floor,round,power,sqrt,mod,sign,trunc - General:
coalesce,cast
- Aggregate:
WHERE IN/WHERE NOT INsupport forSelect,Update, andDeletequery builders with parameterized list/tuple valuesclsparameter onRepository.fetch_one(),fetch_by_field(),fetch_where(),fetch_all(), andfetch_all_ordered()to override the default record class- Dataclass and plain class support in
Cursor.fetchone(),fetchall(), andexec()— classes withoutfromrecordare instantiated viacls(**dict(row))
- ClickHouse backend support via
clickhouse-connectHTTP clientClickHouseConnection— connection wrapper with DB-API 2.0 compatible cursor and client wrappersClickHouseRepository— repository with ClickHouse mutation syntax (ALTER TABLE ... UPDATE/DELETE)ClickHouseManager— database introspection usingsystem.*tablesClickHouseMigrationManager— forward-only migration manager for ClickHouseClickHouseUpdate/ClickHouseDelete— SQL builders generating ClickHouse mutation syntaxClickHouseSqlDialect— dialect with ClickHouse-specific placeholders, JSON functions, and noINSERT...RETURNING
- ClickHouse integration tests using
tox-dockerwithclickhouse/clickhouse-server:25.8 clickhouse-connect>=0.7.0added to dev dependenciesMySqlSqlDialect— MySQL SQL dialect for the query builder, with backtick identifier quoting,%splaceholders, JSON support (JSON_EXTRACT,JSON_UNQUOTE,JSON_CONTAINS,JSON_CONTAINS_PATH), noINSERT...RETURNING, noILIKE(usesUPPER()fallback in DbGrid)json_excludeparameter on@fieldmapperdecorator to exclude fields fromasdict()serialization at the class levelexcludeparameter onasdict()for per-call field exclusion, merged with class-level defaults- Excluded fields remain accessible via attribute access,
asrecord(),fields(), andvalues()
- Updated
tox.inito include ClickHouse docker service alongside PostgreSQL
- sql/dialect.py: Fixed SQL identifier quoting across all dialects (PostgreSQL, SQLite, ClickHouse) to escape embedded double-quotes by doubling them (SQL standard). Previously,
dialect.table(),dialect.field(), anddialect.database()wrapped names in double-quotes without escaping, allowing identifier injection in Manager DDL methods (create_database,drop_database,drop_table,drop_view)
- Nested transaction support via savepoints in
Repository.transaction()context manager; inner transaction failures automatically doom the outer transaction - Python 3.12, 3.13, and 3.14 support in classifiers, CI matrix, and tox environments
Repository.transaction(),begin(),commit(),rollback()documented in repository docs
- Dropped Python 3.9 support (
pytest9.x requires Python >=3.10) - Bumped
psycopg2dependency from>=2.9.2to>=2.9.11(required for Python 3.13+ support) - Removed Python 3.8 classifier (already unsupported via
python_requires = >=3.9) - Updated dev dependencies to latest versions:
pytest8.3.4 -> 9.0.2pytest-cov4.0.0 -> 7.0.0pytest-testdox3.0.1 -> 3.1.0flake86.0.0 -> 7.3.0flake8-black0.3.6 -> 0.4.0coverage7.2.5 -> 7.13.4tox4.5.1 -> 4.49.1psycopg2-binary2.9.3 -> 2.9.11mkdocs-material9.2.7 -> 9.7.4
- CI: bumped
actions/checkoutto v4,actions/setup-pythonto v5, addedallow-prereleases: truefor Python 3.14 - CI: modernized publish workflow to use
python -m build --sdist
- connection.py: Renamed
ConnectionErrortoDbConnectionErrorto avoid shadowing the Python builtin; backward-compatible alias preserved - connection.py: Fixed
cursor()context manager to guard againstUnboundLocalErrorifget_cursor()raises - connection.py: Fixed
!= Nonecomparison to useis not None - repository.py: Fixed
transaction()context manager to properly rollback on exceptions instead of silently swallowing them - repository.py: Fixed
conn()context manager to guard againstUnboundLocalErrorifgetconn()raises; addedeliffor pool branch and raisesRepositoryErrorif no connection or pool is available - profiler/profilers.py: Fixed
filter_duration()using non-existent attributee.durationinstead ofe.elapsed - dbgrid.py: Fixed search mask using
.format()which would raiseKeyErroron brace characters in search text; replaced with.replace("{}", search_str)
- pg/manager.py: Fixed
create_database()overwriting theargsparameter with kwargs processing; uses separatepartslist - pg/manager.py: Fixed
create_database()anddrop_database()not saving/restoring the original isolation level - pg/manager.py: Fixed
conn()context manager to useif/elif/elsepattern withUnboundLocalErrorguard - pg/pginfo.py: Fixed
conn()context manager with sameif/elif/elsepattern and guard - pg/pginfo_records.py: Fixed typo in
DatabaseRecord.id_ownerfield name ("datba"corrected to"datdba") - pg/pool.py: Fixed
getconn()to also catchpsycopg2.InterfaceErrorand added genericexcept Exceptionthat safely returns connection to pool before re-raising - pg/pool.py: Fixed
putconn()to rollback any open transaction before returning connection to pool
- sqlite/connection.py: Added automatic URI detection -
uri=Trueis now passed tosqlite3.connect()whendb_filestarts with"file:" - sqlite/manager.py: Removed
CASCADEfromdrop_table()anddrop_view()as SQLite does not support this syntax - sqlite/migrations.py: Replaced
executescript()with statement-by-statementexec()to avoid implicit commits that broke transaction semantics
- sql/select.py: Fixed duplicate alias error message using literal
{tbl}instead of the actual alias value
- cli/commands/check.py: Fixed call to non-existent
self._tty.title()method; changed toself._tty.header() - cli/commands/flatten.py: Added missing
return Trueafter successful flatten operation - cli/commands/dto.py: Fixed success message saying "DAO" instead of "DTO"
- cli/config.py: Fixed passfile handling storing password under the raw config key instead of using
self.KEY_PASSWORD/self.KEY_PASSFILEconstants
- migrations.py: Added documentation comment noting that
execute()is not transactional between SQL execution and migration registration
- Fixed
ConnectionErrorreferences toDbConnectionErrorthroughout docs - Fixed
Profilerreferences toProfilerInterfacein profiler and related docs - Added transaction methods (
begin(),commit(),rollback(),transaction()) to repository documentation - Fixed
update_whereexample (wrong method name and missing operator) - Fixed
DbGridclass path fromrick_db.sql.DbGridtorick_db.DbGrid - Fixed
Registry.fetch_pk()typo toRepository.fetch_pk() - Fixed
repo.Select()torepo.select()(lowercase) - Fixed CLI commands in CLAUDE.md:
installtoinit,applytomigrate - Modernized install docs: replaced
python3 setup.py installwithpip install .
- Consolidated PG test classes using parametrized fixtures (
test_manager.py,test_pginfo.py,test_migrations.py) - Decoupled
base_repository.pyfrom backend-specific imports (PgConnection,PgConnectionPool,Sqlite3Connection) - Decoupled
base_cursor.pyfrom psycopg2; movedtest_duplicate_recordto PG-specific test classes - Extracted shared helper functions in PG repository and dbgrid tests (
_setup_users,_teardown_users,_setup_grid,_teardown_grid) - Created
tests/backend/sqlite/common.pyfor shared SQLite DDL constants - Fixed
sqlite_connfixture teardown to useyield+close()pattern - Removed redundant
close()call in SQLite cursor test fixture - Fixed trailing whitespace and Black formatting across
rick_db/sql/and test files
- tests/conftest.py: Changed
sqlite_connfixture from"file::memory:"to":memory:"to fix test isolation (URI was treated as a literal filename withouturi=True, causing shared state between tests) - tests/repository/test_sqlite_repository.py: Changed fixture from
"file::memory:?cache=shared"to":memory:"(shared cache unnecessary for single connection) - tests/dbgrid/test_sqlite_dbgrid.py: Same fix as above
- tests/backend/sqlite/test_connection.py: Added
DROP TABLE test3cleanup intest_transaction_rollback_multifor Python < 3.12 where DDL rollback is not supported - tests/backend/sqlite/test_manager.py: Fixed
drop_table("animals")todrop_table("animal")(table name mismatch) - tests/repository/base_repository.py: Fixed tautological assertion
len(users) == len(users)to compare againstlen(fixture_users) - tests/repository/base_repository.py: Fixed
isinstancechecks usingself.conninstead of theconnfixture parameter