baobao_codegen/adapters/database.rs
1//! Database adapter abstraction.
2//!
3//! This module defines the [`DatabaseAdapter`] trait for abstracting database
4//! connection and pool code generation (sqlx, diesel, bun:sqlite, etc.).
5
6use baobao_ir::DatabaseType;
7// Re-export IR types for convenience
8pub use baobao_ir::{PoolConfig, SqliteOptions};
9
10use super::cli::{Dependency, ImportSpec};
11use crate::builder::Value;
12
13/// Info needed to generate pool initialization.
14#[derive(Debug, Clone)]
15pub struct PoolInitInfo {
16 /// Field name in the context struct
17 pub field_name: String,
18 /// Database type
19 pub db_type: DatabaseType,
20 /// Environment variable for connection string
21 pub env_var: String,
22 /// Pool configuration
23 pub pool_config: PoolConfig,
24 /// SQLite-specific config (only for SQLite)
25 pub sqlite_config: Option<SqliteOptions>,
26}
27
28/// Trait for database adapters.
29///
30/// Implement this trait to support a specific database library (sqlx, diesel, etc.).
31pub trait DatabaseAdapter {
32 /// Adapter name for identification.
33 fn name(&self) -> &'static str;
34
35 /// Dependencies required for a specific database type.
36 fn dependencies(&self, db_type: DatabaseType) -> Vec<Dependency>;
37
38 /// The type name for a connection/pool.
39 fn pool_type(&self, db_type: DatabaseType) -> &'static str;
40
41 /// Generate pool/connection initialization as a semantic Value.
42 ///
43 /// Returns a `Value` that represents the initialization expression.
44 /// The caller is responsible for rendering it with the appropriate language renderer.
45 fn pool_init(&self, info: &PoolInitInfo) -> Value;
46
47 /// Imports needed for database code.
48 fn imports(&self, db_type: DatabaseType) -> Vec<ImportSpec>;
49
50 /// Whether this adapter requires async initialization.
51 fn requires_async(&self, db_type: DatabaseType) -> bool;
52}