Skip to main content

systemprompt_database/
lib.rs

1//! # systemprompt-database
2//!
3//! `PostgreSQL` infrastructure for systemprompt.io: a thin `SQLx`-backed pool,
4//! generic repository traits, dynamic-query primitives for admin tooling, and
5//! lifecycle helpers (schema installation, extension migrations, validation).
6//!
7//! ## Public API surface
8//!
9//! - [`Database`] / [`DbPool`] — owned pool wrapper with optional split
10//!   read/write providers.
11//! - [`DatabaseProvider`] — dyn-safe trait abstracting
12//!   query/execute/transaction primitives across providers (currently only
13//!   `PostgreSQL`).
14//! - [`PostgresProvider`] — the `PostgreSQL` implementation.
15//! - [`DatabaseResult`] — result alias over the workspace's single
16//!   [`systemprompt_traits::RepositoryError`].
17//! - [`MigrationService`], [`install_extension_schemas_full`] — lifecycle
18//!   helpers driving extension-supplied DDL.
19//! - [`DatabaseAdminService`], [`QueryExecutor`], [`AdminSql`],
20//!   [`SafeIdentifier`] — admin/introspection layer used by the CLI.
21//! - [`resilience`] — domain-agnostic resilience primitives
22//!   ([`resilience::ResilienceGuard`], [`resilience::CircuitBreaker`],
23//!   [`resilience::Bulkhead`], [`resilience::retry_async`]) wrapping outbound
24//!   calls; the crate's own connection and transaction retries run on them.
25//!
26//! ## Feature flags
27//!
28//! This crate currently has no Cargo features; everything compiles
29//! unconditionally. The `[package.metadata.docs.rs]` block is in place so
30//! `--all-features` documentation builds remain stable as features are added.
31//!
32//! ## sqlx allowlist
33//!
34//! Static SQL goes through the compile-time-verified `sqlx::query!` /
35//! `query_as!` / `query_scalar!` macros. Runtime/dynamic SQL is contained to
36//! two paths whose contract is dynamic SQL by design; the `lint-sqlx` gate
37//! allows runtime `sqlx::query` only there:
38//!
39//! - `src/admin/` — admin CLI surfaces (introspection, restricted query
40//!   executor) where the SQL is the user input.
41//! - `src/services/postgres/` — the dyn-safe `DatabaseProvider` implementation,
42//!   transaction wrapper, type-erased helpers and `PostgreSQL` schema
43//!   introspection.
44//! - `src/projection/` — `drain_with_sql` calls the projector function the
45//!   caller names (validated as a bare identifier); the name is the only
46//!   dynamic part and no value is interpolated.
47//!
48//! Every other call site uses verified macros.
49//!
50//! ## Data paradigm
51//!
52//! [`projection`] documents the rule every analytics-shaped read follows:
53//! store the answer when the row is written, read the stored answer. Raw
54//! ledger tables are read by projectors and single-entity detail queries
55//! only; the queue, drainer and backfill detector that make that hold live
56//! there and in [`backfill_statements`].
57//!
58//! Copyright (c) systemprompt.io — Business Source License 1.1.
59//! See <https://systemprompt.io> for licensing details.
60
61pub mod admin;
62pub mod error;
63pub mod extension;
64pub mod lifecycle;
65pub mod models;
66pub mod projection;
67#[macro_use]
68pub mod repository;
69pub mod resilience;
70pub mod services;
71
72pub use extension::DatabaseExtension;
73
74pub use models::{
75    ColumnInfo, DatabaseInfo, DatabaseQuery, DatabaseTransaction, DbValue, FromDbValue, IndexInfo,
76    JsonRow, QueryResult, QueryRow, QuerySelector, TableInfo, ToDbValue, escape_like,
77    parse_database_datetime,
78};
79
80pub use services::{
81    BoxFuture, BudgetedDb, Database, DatabaseCliDisplay, DatabaseExt, DatabaseProvider, DbPool,
82    PoolConfig, PostgresProvider, SchemaEpoch, SqlExecutor, with_transaction_retry,
83};
84
85pub use error::DatabaseResult;
86pub use lifecycle::{
87    AppliedMigration, BOOTSTRAP_ADVISORY_LOCK_KEY, BackfillStatement, BaselineStamp,
88    BootstrapLockGuard, BootstrapLockTimeout, ChecksumDrift, DeferredForeignKey,
89    ExpensiveStatement, ExtensionMigrationStatus, FkDeferralError, ForeignKeyDrift, FreshnessCheck,
90    HOT_TABLES, MarkAppliedOutcome, MigrationConfig, MigrationCost, MigrationResult,
91    MigrationService, MigrationStatus, OrphanMigrationLedger, OrphanedMigration,
92    PROJECTION_BACKLOG, PendingMigration, RETRYABLE_SQLSTATES, RepairResult, ReplicaStatus,
93    SchemaAhead, SchemaCurrency, SchemaInstallReport, SchemaResidue, SlotCollision,
94    SplitCreateTable, TombstonedSlot, UndeclaredTable, audit_migration_cost, audit_one,
95    audit_schema_residue, backfill_statements, check_migration_references, check_trigger_routines,
96    install_extension_schemas_full, is_retirement, is_retryable_lock_conflict,
97    is_retryable_sqlstate, projection_tables, replica_status, schema_catalog_digest,
98    schema_currency, split_create_table_foreign_keys, validate_column_exists,
99    validate_database_connection, validate_table_exists, validate_write_pool_is_primary,
100};
101pub use repository::{
102    CLAIM_DEAD_PEER_SECS, CoordinationRepositories, CreateServiceInput, EXTENSION_LOCK_CLASS,
103    INSTANCE_CLAIM_CLASS, INSTANCE_DEAD_AFTER_SECS, InstanceClaim, InstanceClaimError,
104    InstanceLeaseRepository, PLANE_NOT_APPLIED_HINT, PROCESS_OWNERSHIP_CHANNEL, PgConfigVersion,
105    PgDbPool, PlaneTransaction, ProcessOwner, ProcessOwnershipWake, Reaped, ReapedService,
106    ReleaseGate, ReleaseRun, ReleaseStampError, ReleaseStampRepository, RoleCount, ServiceConfig,
107    ServiceModule, ServiceRepository, ServiceStatus, SessionAdvisoryLock, SessionAdvisoryLocks,
108    StampOutcome, UpsertServiceProcessInput, find_config_plane_applied,
109    record_config_plane_applied, release_key, with_change_context,
110};
111
112pub use admin::{
113    AdminSql, AdminSqlError, DEFAULT_READONLY_ROW_LIMIT, DatabaseAdminService, IdentifierError,
114    QueryExecutor, QueryExecutorError, SafeIdentifier,
115};
116
117use systemprompt_traits::DatabaseHandle;
118
119impl DatabaseHandle for Database {
120    fn is_connected(&self) -> bool {
121        !self.pool().is_closed() && !self.write_pool().is_closed()
122    }
123
124    fn as_any(&self) -> &dyn std::any::Any {
125        self
126    }
127}