{"data":{"slug":"discovered-17aefd1c56aa420b6eb64b4b3cdbbdbeb4a3d516cd144932","title":"Rust Database Layer Implementation and Management","summary":"Design, implement, and manage a migration-compatible, rollback-capable, and observable data access layer in Rust, aligned with specific database dialects, schemas, and transaction semantics. Deliverables include connection pools, repository implementations, queries, migrations, and real-database verification.","url":"https:\/\/skillshunter.net\/skills\/discovered-17aefd1c56aa420b6eb64b4b3cdbbdbeb4a3d516cd144932","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/discovered-17aefd1c56aa420b6eb64b4b3cdbbdbeb4a3d516cd144932","markdown_url":"https:\/\/skillshunter.net\/skills\/discovered-17aefd1c56aa420b6eb64b4b3cdbbdbeb4a3d516cd144932.md","download_url":"https:\/\/skillshunter.net\/skills\/discovered-17aefd1c56aa420b6eb64b4b3cdbbdbeb4a3d516cd144932\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Before starting, collect information about the database product, exact version, extensions, deployment topology, read\/write nodes, and current schema constraints. Validate the Rust toolchain\/MSRV, synchronous or asynchronous execution models, and establish connection limits, instance counts, timeouts, and transaction isolation levels.","instructions":"---\ndescription: Design, implement, migrate, test, and operate Rust database access, including SQLx, Diesel, SeaORM, schema evolution, transaction boundaries, connection pools, retries, type mapping, concurrency control, and real-database verification. Use when users ask about Rust SQL or ORM code, migrations, transactions, PostgreSQL or MySQL integration, connection pools, query safety, or database production readiness.\nlicense: Apache-2.0\nmetadata:\n    github-path: skills\/rust-database\n    github-ref: refs\/heads\/main\n    github-repo: https:\/\/github.com\/full-stack-skills\/rust-skills\n    github-tree-sha: 1e0a73a922b5085d3e6e1243f2a8cbd58c1c2b5d\nname: rust-database\n---\n# Rust Database Layer Delivery\n\nDeliver a migration-compatible, rollback-capable, and observable data access layer based on the actual dialects, schemas, and transaction semantics of databases. Do not treat HTTP handlers as repositories; do not use mocks to validate real database behavior.\n\n## Confirming Database Contracts\n\nBefore modifications:\n- Collect information about the database product, exact version, extensions, deployment topology, read\/write nodes;\n- Gather current schema constraints, indexes, triggers, views, and migration history;\n- Identify locked versions of SQLx, Diesel, SeaORM (or other access stacks) along with their features;\n- Determine Rust toolchain\/MSRV, synchronous or asynchronous execution models;\n- Establish connection limits, instance counts, timeouts, transaction isolation levels, and consistency requirements;\n- Define data volume profiles, hot query patterns, pagination strategies, retention policies, and archival needs;\n- Document credential sources, TLS configurations, tenant boundaries, row-level permissions, and audit requirements;\n- Clarify whether deployments allow downtime, double writes, backfills, or destructive DDL operations.\n\nWhen real database access is unavailable, distinguish between \"code\/offline metadata validation\" and \"real dialect validation.\" Do not conflate these two approaches in reporting.\n\n## Workflow\n\n### 1. Establish Current Baseline\n```bash\nrustc --version --verbose\ncargo metadata --format-version 1\ncargo tree -e features\ncargo test --all-targets\n```\nLocate connection initialization, pool configuration, repository implementations, queries, migrations, test fixtures, and CI database connections. Execute existing migration status\/check commands; do not run operations that modify shared databases without explicit authorization.\n\n### 2. Preserve Existing Access Stacks\nAvoid rewriting solely based on preference among SQLx, Diesel, or SeaORM. Select the appropriate stack according to current codebase and task requirements:\n- **SQLx**: Requires direct SQL access, asynchronous querying, and optional compile-time query validation;\n- **Diesel**: Utilizes typed DSL queries, synchronous connections, or existing Diesel schemas;\n- **SeaORM**: Leverages async ORM\/entity models with corresponding migration systems;\n- **Native database drivers**: Reserved for cases where protocol or functionality does not support a generic layer, though expanding maintenance and security review scope.\n\nSpecific selection criteria and type boundaries are documented in [Access Stack and Types](references\/access-stack-and-types.md). All APIs must align with the versioned documentation from `Cargo.lock`, avoiding direct application of latest examples to legacy projects.\n\n### 3. Let Schema Constraints Enforce Facts\n- Define primary keys, uniqueness constraints, foreign keys, non-null checks, and check constraints as immutable invariants guaranteed by the database;\n- Rust types express domain semantics but cannot replace cross-process concurrency guarantees provided by databases;\n- Explicitly specify integer widths, decimal precision, timezones, UUIDs, JSON formats, nullability mappings;\n- Bind parameters to all queries. Use dynamic identifiers or sort fields only via allowlists and type mapping\u2014not as regular bind values pretending to be safe;\n- Restrict column selection to necessary columns to avoid reliance on unstable `SELECT *` layouts;\n- Prioritize stable sorting strategies and keyset-based pagination over unbounded offset operations under high data volumes.\n\n### 4. Design Migrations Before Code Changes\nFor each schema change, document:\n1. Forward DDL statements;\n2. Compatibility windows between old and new versions for applications;\n3. Data backfill methods, batch sizes, and rollback points;\n4. Index construction risks and lock contention implications;\n5. Rollback or forward recovery strategies;\n6. Validation queries, monitoring metrics, and termination conditions.\n\nAdopt the sequence: expand \u2192 backfill \u2192 switch \u2192 contract. Destructive operations\u2014column deletion, type changes, large table reconstruction, data clearing, irreversible backfills\u2014require explicit target parsing and authorization details found in [Migrations and Schema Evolution](references\/migrations-and-schema.md).\n\n### 5. Place Transactions Within Complete Use Cases\n- Initiate transactions via application services or repository unit-of-work units; do not commit transactionally across HTTP handlers indiscriminately;\n- Ensure atomic success of writes within a single shared transaction and connection set;\n- Avoid unbounded user interactions outside the transaction scope, including unnecessary external HTTP waits inside transactions;\n- Select isolation levels per database documentation to identify risks such as lost updates, write skew, phantom reads;\n- Retry only transient errors explicitly identified by the database. Set retry counts, backoff strategies, and idempotency boundaries;\n- Commit failures are possible; do not treat \"last SQL statement success\" as transactional completion;\n- Drop\/rollback serves as a safety net but does not replace explicit control flow design or testing practices.\n\nConnection pooling, isolation levels, and retry mechanisms are detailed in [Transactions and Pooling](references\/transactions-and-pooling.md).\n\n### 6. Design Stable Data Access Interfaces\n```text\napplication use case\n  -> repository \/ unit of work port\n  -> SQL\/ORM adapter\n  -> database\n```\n- Repository methods should accept domain parameters and results without leaking Web DTOs;\n- Classify errors into categories: not found, uniqueness conflicts, foreign key violations, serialization failures, timeouts, unavailability;\n- Preserve full error chains for logging and diagnostics while preventing sensitive SQL parameter exposure in user responses;\n- Batch interfaces must define ordering semantics, partial failure handling, idempotency guarantees, and return row counts;\n- Avoid N+1 queries. Validate performance under realistic data scales when pre-fetching joins or batching is required.\n\n### 7. Configure Limited Connection Budgets\nValidate total connection budgets using the formula: `(per-instance pool limit \u00d7 maximum instance count) + operational connections`. Set acquire, connect, statement, and transaction timeouts; define idle\/max lifetimes, health checks, and graceful shutdown procedures. Do not instantiate a new pool per request nor let indefinite waits mask resource exhaustion issues.\n\n### 8. Validate with Real Engines\nConduct at least the following validations:\n1. Execute all migrations from an empty database;\n2. Upgrade schema versions supported by existing databases;\n3. Verify repository success, missing records, constraint conflicts, and type boundaries;\n4. Test transaction commits, rollbacks, commit failures, and retryable concurrency issues;\n5. Ensure invariants hold under concurrent writes;\n6. Confirm query plans, index hits, and representative data volumes;\n7. Assess pool exhaustion scenarios, database restarts\/disconnections, and graceful shutdown behaviors;\n8. Verify logs, metrics, and traces do not leak bound values or credentials.\n\nTest execution and operation lists are provided in [Testing and Operations](references\/testing-and-operations.md).\n\n## Common Gates (Gateways)\n\n```bash\ncargo fmt --all -- --check\ncargo check --all-targets\ncargo test --all-targets\ncargo clippy --all-targets -- -D warnings\n```\nRun repository-specific migration validation, SQLx offline metadata checks, Diesel schema audits, or real database integration tests. Commands and features may vary by version; consult project configuration first.\n\n## Completion Criteria\n- Database versions, schemas, access stacks, and consistency assumptions are clearly defined;\n- All queries use parameterization with dynamic identifiers filtered via allowlists;\n- Migration compatibility windows, backfill strategies, recovery procedures, and destructive boundaries are documented;\n- Transaction coverage spans complete use cases with justified connection budgets and timeouts;\n- Real database testing validates migrations, constraints, rollbacks, and concurrency risks;\n- fmt, check, test, Clippy pass; unvalidated real-database tests must be explicitly marked.\n\n## Handoff Boundaries\n\n| Primary Responsibility | Assigned To |\n|---|---|\n| HTTP routing, handlers, status codes, middleware | `rust-web` |\n| Credentials, tenant authorization, audit logs, sensitive field exposure | `rust-web-security` |\n| Async cancellation, locks, tasks, blocking isolation | `rust-concurrency` |\n| Test layering, coverage metrics, performance baselines | `rust-testing` |\n| Features, build scripts, offline metadata, release pipelines | `rust-cargo-build` |\n| Types, ownership semantics, error traits, standard library behavior | [rust-best-practices](..\/rust-best-practices\/SKILL.md) |\n\n## On-Demand Resources\n- [Access Stack and Types](references\/access-stack-and-types.md): Consult when selecting or adapting SQLx, Diesel, SeaORM, or type mappings.\n- [Migrations and Schema Evolution](references\/migrations-and-schema.md): Review DDL design, compatibility backfills, and recovery strategies.\n- [Transactions and Pooling](references\/transactions-and-pooling.md): Refer for atomicity guarantees, isolation levels, retry logic, and capacity management.\n- [Testing and Operations](references\/testing-and-operations.md): Access real-database test setups, query plans, observability practices.\n- [Scenario Examples](examples\/examples.md): Use this template when end-to-end task decomposition is required.\n- `examples\/golden-transaction\/`: Offline compilation and validation of transaction boundary examples available here.\n\n## References\n- [`std::error`](https:\/\/doc.rust-lang.org\/stable\/std\/error\/) (Rust Standard Library)\n- [SQLx documentation](https:\/\/docs.rs\/sqlx\/)\n- [Diesel guides](https:\/\/diesel.rs\/guides\/)\n- [SeaORM documentation](https:\/\/www.sea-ql.org\/SeaORM\/)\n","use_cases":["Design and implement Rust database access layers using SQLx, Diesel, or SeaORM","Perform schema evolution and migration status checks","Configure connection pools with limited budgets and timeouts","Validate real-database behavior and ensure query safety","Ensure compatibility with versioned documentation from Cargo.lock"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/sajaddp\/sonjoo-seo-audit\/blob\/b53a2eae486acf635a0b1dbd76be236343deb4b2\/.agents\/skills\/rust-database\/SKILL.md","source_commit":"b53a2eae486acf635a0b1dbd76be236343deb4b2","license":null,"version":null,"listing_approved_at":"2026-11-30","created_at":"2026-11-29T11:05:09.000000Z","updated_at":"2026-11-30T06:52:12.000000Z","seo_title":"Rust Database Layer Implementation and Management","seo_description":"Implement and manage a robust, migration-compatible, and observable data access layer in Rust, aligned with specific database dialects, schemas, and transaction semantics","seo_keywords":["Rust database","SQLx","Diesel","SeaORM","database migration","connection pool","Rust ORM","database access layer"]}}