db-cores
Database core utilities for Rust. A SQL abstraction toolkit providing multi-database support (PostgreSQL, MySQL, SQLite) with query building, connection management, and schema utilities.
Overview
db-cores provides a unified interface for working with multiple SQL databases in Rust:
-
Query Building — Generic SQL query builders with type-safe parameter binding, using sqlx's
Databasetrait for cross-database compatibility. Supports SELECT, INSERT, UPDATE, DELETE with conditions, pagination, and ordering. -
SQL Generation — Database-specific SQL generation for PostgreSQL, MySQL, and SQLite. Supports generating SQL from JSON structures and simplified query structures.
-
JSON Conversion — Convert database rows (
PgRow,MySqlRow,SqliteRow) toserde_json::Valuewith automatic type mapping. -
Connection Pool Management — Global connection pool cache with
DbPoolenum wrappingMySqlPool,PgPool, andSqlitePool. Supports auto-creation and caching. -
Plugin System — Database-specific plugins (e.g.,
pg_get_tabledeffor PostgreSQL). -
Macro System — Procedural macros including:
define_model!— Generates struct withFromRow,Serialize,Deserializedefine_enum!— Generates enum with sqlxDecode/Typeand serde traitsSqlxEnumderive macropg_builder!— Parameterized Postgres query builder
-
Schema Utilities — Table creation, alteration, and comparison (diff detection for columns and tables).
-
AST Parsing — SQL AST parsing using
sqlparser. -
Validation — SQL identifier validation.
Features
The crate uses feature flags to control which database backends are included. sqlx is an optional dependency — it's only pulled in when at least one database feature is enabled.
[]
= ["postgres"]
= ["dep:sqlx", "sqlx/postgres"]
= ["dep:sqlx", "sqlx/mysql"]
= ["dep:sqlx", "sqlx/sqlite"]
Usage
Add to your Cargo.toml:
# Default (PostgreSQL only)
= "0.1.0"
# SQLite only
= { = "0.1.0", = false, = ["sqlite"] }
# MySQL only
= { = "0.1.0", = false, = ["mysql"] }
# PostgreSQL + MySQL
= { = "0.1.0", = ["mysql"] }
# All databases
= { = "0.1.0", = ["postgres", "mysql", "sqlite"] }
# No database (SQL building utilities only)
= { = "0.1.0", = false }
Quick Examples
Define a Model
use define_model;
define_model!;
Get a Connection Pool
use ;
let connect = DbConnect ;
let pool = postgres_pool.await?;
Modules
query— Database-specific query execution (postgres,mysql,sqlitesubmodules)builder— SQL query builder with type-safe parameter bindingto_json— Row-to-JSON conversion for each database backendcommon— Shared types (DbConnect,DatabaseKind,TableColumn, etc.)plugin— Database-specific pluginsast— SQL AST parsing utilitiesverify— SQL identifier validationutlis— General utilities
Links
- Repository: https://github.com/Kaifang-123/db-cores
- Documentation: https://docs.rs/db-cores
License
MIT