# BR-DB PROJECT KNOWLEDGE BASE
**Generated:** 2026-02-08
**Commit:** 654820c
**Branch:** main
## OVERVIEW
Multi-database ORM library for Rust supporting MySQL, PostgreSQL, SQLite, and MSSQL with fluent query builder API, transaction management, and JSON field handling. Global-state architecture (not instance-scoped).
## STRUCTURE
```
br-db/
├── src/
│ ├── lib.rs # Db enum, global state (lazy_static), connection management, fluent API (~1285 lines)
│ ├── config.rs # Config, Connection, Mode, PoolConfig, Charset
│ ├── error.rs # DbError enum (16 variants) with thiserror
│ ├── pools.rs # Thread pool (Worker/Pool) for batch insert operations
│ ├── fields.rs # Field/Fields enums for schema definition (30 field types)
│ └── types/ # Database backend implementations (see types/AGENTS.md)
├── tests/ # Integration tests per database (7 files, require live DBs)
└── examples/ # Data migration script + config.toml (shared test config)
```
## WHERE TO LOOK
| Add new DB backend | `src/types/` | Implement `Mode` + `DbMode` traits |
| Connection config | `src/config.rs` | `Connection`, `PoolConfig`, `Charset` structs |
| Query building | `src/types/mod.rs` | `Params` struct, `Mode` trait (50+ methods) |
| Error handling | `src/error.rs` | `DbError` enum, `DbResult` type alias |
| Transaction logic | `src/types/*_transaction.rs` | Per-backend thread-keyed managers |
| SQL injection prevention | `src/types/mod.rs:5-180` | `sql_safety` module with unit tests |
| Schema/field definitions | `src/fields.rs` | `Fields` enum (30 types), `Field` builder |
| Batch operations | `src/pools.rs` | `Pool`/`Worker` for parallel insert_all |
| Global DB registry | `src/lib.rs:33` | `lazy_static!` — DB, CONNECTION, DEFAULT, TABLE_FIELDS |
| Table DDL | `src/lib.rs:1228` | `Table` struct with `parse()`/`to_str()` |
## CODE MAP
| `Db` | enum | `lib.rs:39` | Main entry — Mysql/Sqlite/Mssql/Pgsql/None variants |
| `Db::load` | fn | `lib.rs:53` | Init from config file path |
| `Db::new` | fn | `lib.rs:64` | Init from `Config` struct |
| `Db::connection` | method | `lib.rs:144` | Switch active connection by name |
| `Table` | struct | `lib.rs:1228` | DDL schema definition (version, fields, indexes, partitions) |
| `Mode` | trait | `types/mod.rs:271` | Core query interface (50+ methods) |
| `DbMode` | trait | `types/mod.rs:209` | Database-level ops (tables, create, backups) |
| `Params` | struct | `types/mod.rs:374` | Query state accumulator (25 fields) |
| `TableOptions` | struct | `types/mod.rs:220` | Table creation options |
| `sql_safety` | module | `types/mod.rs:5` | SQL injection prevention (validate, escape) |
| `quote_identifier` | fn | `types/mod.rs:184` | Dialect-aware identifier quoting |
| `Config` | struct | `config.rs:7` | Multi-connection configuration |
| `Connection` | struct | `config.rs:180` | Single DB connection params (12 fields) |
| `PoolConfig` | struct | `config.rs:143` | Connection pool tuning (min/max/timeouts) |
| `Mode` (config) | enum | `config.rs:111` | Mysql/Mssql/Sqlite/Pgsql/None |
| `Charset` | enum | `config.rs:304` | Utf8mb4/Utf8/None |
| `DbError` | enum | `error.rs:3` | 16 error variants (Config, Connection, Query, SqlInjection...) |
| `DbResult` | type | `error.rs:51` | `Result<T, DbError>` alias |
| `Fields` | enum | `fields.rs:2` | 30 field types (String, Int, Json, DateTime...) |
| `Field` | struct | `fields.rs:55` | Field builder with fluent API |
| `Pool` | struct | `pools.rs:55` | Thread pool for batch operations |
## CONVENTIONS
- **Feature flags**: `db-mysql`, `db-sqlite`, `db-mssql`, `db-pgsql` (all default-enabled)
- **ID generation**: Hex timestamp + thread ID when `autoinc=false`
- **JSON fields**: Mark with `.json("field")` before insert/update/select
- **Location fields**: Mark with `.location("field")` for geo coordinates
- **Chinese comments**: Doc comments in Chinese throughout codebase
- **Global state**: `lazy_static!` for DB, CONNECTION, DEFAULT, TABLE_FIELDS (not instance-scoped)
- **Query returns**: `(bool, JsonValue)` tuple — success flag + data/error
- **Re-exports**: Only `DbError`/`DbResult` re-exported at crate root
- **No formatting/lint config**: No `.rustfmt.toml`, `clippy.toml`, or `.editorconfig` — uses defaults
## ANTI-PATTERNS (THIS PROJECT)
- **MSSQL incomplete**: 16 `todo!()` stubs in `types/mssql.rs` — insert, update, delete, transaction, inc, dec, location all panic
- **No CI**: Build/test is manual; no GitHub Actions, Makefile, or build.rs
- **Hardcoded test creds**: `111111` password in tests and `examples/config.toml`
- **Nested transactions**: Not supported (see `tests/pgsql.rs:449`)
- **Test duplication**: `pgsql.rs` and `sqlite.rs` tests are near-identical; no shared `tests/common.rs`
- **Module naming mismatch**: `tests/mysql.rs` defines `mod pgsql` internally (copy-paste artifact)
- **Unsafe in tests**: `unsafe { env::set_var() }` in `tests/mysql.rs:11`, `tests/pgsql.rs:14`
- **Machine-specific paths**: Absolute SQLite path in `examples/config.toml`
## UNIQUE STYLES
- **Fluent API**: Chain methods like `.table("x").where_and("a","=",v).select()`
- **Pipe OR syntax**: `where_and("field1|field2", "like", v)` splits to OR conditions
- **Compare operators**: Custom set including `set`, `notin`, `isnot`, `notlike`
- **Batch insert**: Uses thread pool (`pools.rs`) for parallel value generation
- **Config loading**: `Config::create(PathBuf)` reads TOML with `[br_db]` wrapper struct
## COMMANDS
```bash
# Build
cargo build --all-features
# Test (requires local DB instances)
cargo test --package br-db --test pgsql -- pgsql::connect_test --exact --show-output
# Lint
cargo clippy --all-targets --all-features -- -D warnings
# Publish
cargo publish --dry-run
cargo publish
```
## TESTS
| `tests/mysql.rs` | MySQL | Basic CRUD |
| `tests/pgsql.rs` | PostgreSQL | Full CRUD + transactions (largest suite) |
| `tests/sqlite.rs` | SQLite | Full CRUD + transactions (mirrors pgsql) |
| `tests/pgsql_2.rs` | PostgreSQL | Raw `tokio_postgres` connectivity (bypasses crate API) |
| `tests/concurrent_transaction.rs` | Multi | Concurrency stress with `thread::spawn`/`Barrier` |
| `tests/advanced_transaction.rs` | Multi | Stress/perf/timeout transaction scenarios |
| `tests/dynamic_switch_test.rs` | Multi | Cross-database switching + mixed workloads |
All tests use `Config::create(PathBuf::from("examples").join("config.toml"), false)` for setup.
## NOTES
- Tests require local database instances (see `examples/config.toml`)
- PostgreSQL: `docker run --name postgres -e POSTGRES_PASSWORD=111111 -p 5432:5432 -d postgres`
- Transaction isolation is thread-based via `ThreadId` key
- `br-fields` and `br-pgsql` are sibling crates (commented local paths in Cargo.toml)
- `lib.rs` is both module barrel AND implementation (~1285 lines of fluent API delegation)
- Published crate excludes `examples/` and `tests/` via Cargo.toml `exclude`