adk_kernel/stores/
driver_postgres.rs1use super::driver_sql::{REGISTRY_TABLE, sql_driver_store};
5use crate::error::{KernelError, Result};
6
7const MIGRATIONS: &[(i64, &str, &str)] = &[(
12 1,
13 "create kernel driver and parked-call tables",
14 "\
15CREATE TABLE IF NOT EXISTS adk_kernel_drivers (\
16 id TEXT COLLATE \"C\" PRIMARY KEY, \
17 record TEXT NOT NULL\
18);\
19CREATE TABLE IF NOT EXISTS adk_kernel_driver_parks (\
20 app_name TEXT COLLATE \"C\" NOT NULL, \
21 user_id TEXT COLLATE \"C\" NOT NULL, \
22 session_id TEXT COLLATE \"C\" NOT NULL, \
23 call_id TEXT COLLATE \"C\" NOT NULL, \
24 driver_id TEXT NOT NULL, \
25 park TEXT NOT NULL, \
26 PRIMARY KEY (app_name, user_id, session_id, call_id)\
27);\
28CREATE INDEX IF NOT EXISTS adk_kernel_driver_parks_driver ON adk_kernel_driver_parks (driver_id);",
29)];
30
31#[derive(Debug, Clone)]
49pub struct PostgresDriverStore {
50 pool: sqlx::PgPool,
51}
52
53impl PostgresDriverStore {
54 pub fn new(pool: sqlx::PgPool) -> Self {
56 Self { pool }
57 }
58
59 pub fn pool(&self) -> &sqlx::PgPool {
61 &self.pool
62 }
63
64 pub async fn connect(database_url: &str) -> Result<Self> {
70 let pool =
71 sqlx::PgPool::connect(database_url).await.map_err(|error| KernelError::Store {
72 backend: "postgres",
73 reason: format!("could not connect: {error}"),
74 })?;
75 Ok(Self::new(pool))
76 }
77
78 pub async fn migrate(&self) -> Result<()> {
86 migrate_locked(self.pool.clone()).await
87 }
88}
89
90fn migrate_locked(
93 pool: sqlx::PgPool,
94) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send>> {
95 use sqlx::Connection as _;
96
97 let store_error = |action: &str, error: &dyn std::fmt::Display| KernelError::Store {
98 backend: "postgres",
99 reason: format!("could not {action}: {error}"),
100 };
101 Box::pin(async move {
102 let key = REGISTRY_TABLE
103 .bytes()
104 .fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
105 (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
106 })
107 .cast_signed();
108 let mut lock = sqlx::PgConnection::connect_with(&pool.connect_options())
109 .await
110 .map_err(|error| store_error("connect for the migration lock", &error))?;
111 sqlx::query("SELECT pg_advisory_lock($1)")
112 .bind(key)
113 .execute(&mut lock)
114 .await
115 .map_err(|error| store_error("take the migration lock", &error))?;
116 let result = adk_session::migration::pg_runner::run_sql_migrations(
117 &pool,
118 REGISTRY_TABLE,
119 MIGRATIONS,
120 || async { Ok(false) },
121 )
122 .await
123 .map_err(|error| KernelError::Store { backend: "postgres", reason: error.message });
124 let _ = lock.close().await;
125 result
126 })
127}
128
129sql_driver_store!(PostgresDriverStore, "postgres");