adk_graph/checkpointers/
postgres.rs1use async_trait::async_trait;
4use sqlx::Row;
5use sqlx::postgres::PgPool;
6
7use super::{decode, encode, storage_error};
8use crate::checkpoint::{Checkpointer, RetentionPolicy, conflict, duplicate_id, ensure_newer};
9use crate::error::Result;
10use crate::state::Checkpoint;
11
12const BACKEND: &str = "postgres";
13
14const SCHEMA: [&str; 2] = [
16 "CREATE TABLE IF NOT EXISTS adk_graph_checkpoints (\
17 id TEXT PRIMARY KEY, \
18 thread_id TEXT NOT NULL, \
19 version BIGINT NOT NULL, \
20 created_at TIMESTAMPTZ NOT NULL, \
21 data TEXT NOT NULL, \
22 CONSTRAINT adk_graph_checkpoints_thread_version UNIQUE (thread_id, version))",
23 "CREATE INDEX IF NOT EXISTS adk_graph_checkpoints_thread \
24 ON adk_graph_checkpoints (thread_id, version DESC)",
25];
26
27#[derive(Debug, Clone)]
47pub struct PostgresCheckpointer {
48 pool: PgPool,
49}
50
51impl PostgresCheckpointer {
52 pub async fn new(database_url: &str) -> Result<Self> {
58 let pool = PgPool::connect(database_url)
59 .await
60 .map_err(|e| storage_error(BACKEND, format!("connection failed: {e}")))?;
61 Ok(Self::from_pool(pool))
62 }
63
64 pub fn from_pool(pool: PgPool) -> Self {
66 Self { pool }
67 }
68
69 pub async fn migrate(&self) -> Result<()> {
76 let fail = |e: sqlx::Error| storage_error(BACKEND, format!("migration failed: {e}"));
77 let mut tx = self.pool.begin().await.map_err(fail)?;
78 sqlx::query("SELECT pg_advisory_xact_lock(hashtext('adk_graph_checkpoints'))")
79 .execute(&mut *tx)
80 .await
81 .map_err(fail)?;
82 for statement in SCHEMA {
83 sqlx::query(statement).execute(&mut *tx).await.map_err(fail)?;
84 }
85 tx.commit().await.map_err(fail)
86 }
87
88 async fn head(&self, thread_id: &str) -> Result<u64> {
89 let head: Option<i64> = sqlx::query_scalar(
90 "SELECT MAX(version) FROM adk_graph_checkpoints WHERE thread_id = $1",
91 )
92 .bind(thread_id)
93 .fetch_one(&self.pool)
94 .await
95 .map_err(|e| storage_error(BACKEND, e))?;
96 Ok(head.map_or(0, |head| head as u64))
97 }
98
99 async fn fetch(
100 &self,
101 query: sqlx::query::Query<'_, sqlx::Postgres, sqlx::postgres::PgArguments>,
102 ) -> Result<Vec<Checkpoint>> {
103 let rows = query.fetch_all(&self.pool).await.map_err(|e| storage_error(BACKEND, e))?;
104 rows.iter()
105 .map(|row| {
106 let data: String = row.try_get("data").map_err(|e| storage_error(BACKEND, e))?;
107 decode(BACKEND, &data)
108 })
109 .collect()
110 }
111}
112
113fn version_param(version: u64) -> Result<i64> {
114 i64::try_from(version)
115 .map_err(|_| storage_error(BACKEND, format!("version {version} exceeds BIGINT")))
116}
117
118#[async_trait]
119impl Checkpointer for PostgresCheckpointer {
120 async fn save(&self, checkpoint: &Checkpoint) -> Result<String> {
121 ensure_newer(checkpoint, None)?;
122 let version = version_param(checkpoint.version)?;
123 let inserted = sqlx::query(
124 "INSERT INTO adk_graph_checkpoints (id, thread_id, version, created_at, data) \
125 SELECT $1, $2, $3, $4, $5 \
126 WHERE NOT EXISTS (SELECT 1 FROM adk_graph_checkpoints \
127 WHERE thread_id = $2 AND version >= $3)",
128 )
129 .bind(&checkpoint.checkpoint_id)
130 .bind(&checkpoint.thread_id)
131 .bind(version)
132 .bind(checkpoint.created_at)
133 .bind(encode(checkpoint)?)
134 .execute(&self.pool)
135 .await;
136 match inserted {
137 Ok(result) if result.rows_affected() == 1 => Ok(checkpoint.checkpoint_id.clone()),
138 Ok(_) => Err(conflict(checkpoint, self.head(&checkpoint.thread_id).await?)),
139 Err(sqlx::Error::Database(error)) if error.is_unique_violation() => {
140 if error.constraint() == Some("adk_graph_checkpoints_thread_version") {
141 Err(conflict(checkpoint, self.head(&checkpoint.thread_id).await?))
142 } else {
143 Err(duplicate_id(&checkpoint.checkpoint_id))
144 }
145 }
146 Err(error) => Err(storage_error(BACKEND, error)),
147 }
148 }
149
150 async fn load(&self, thread_id: &str) -> Result<Option<Checkpoint>> {
151 Ok(self
152 .fetch(
153 sqlx::query(
154 "SELECT data FROM adk_graph_checkpoints WHERE thread_id = $1 \
155 ORDER BY version DESC LIMIT 1",
156 )
157 .bind(thread_id.to_string()),
158 )
159 .await?
160 .pop())
161 }
162
163 async fn load_by_id(&self, checkpoint_id: &str) -> Result<Option<Checkpoint>> {
164 Ok(self
165 .fetch(
166 sqlx::query("SELECT data FROM adk_graph_checkpoints WHERE id = $1")
167 .bind(checkpoint_id.to_string()),
168 )
169 .await?
170 .pop())
171 }
172
173 async fn list(&self, thread_id: &str) -> Result<Vec<Checkpoint>> {
174 self.fetch(
175 sqlx::query(
176 "SELECT data FROM adk_graph_checkpoints WHERE thread_id = $1 ORDER BY version ASC",
177 )
178 .bind(thread_id.to_string()),
179 )
180 .await
181 }
182
183 async fn list_page(
184 &self,
185 thread_id: &str,
186 before: Option<u64>,
187 limit: usize,
188 ) -> Result<Vec<Checkpoint>> {
189 let before = before.map_or(Ok(i64::MAX), version_param)?;
190 self.fetch(
191 sqlx::query(
192 "SELECT data FROM adk_graph_checkpoints WHERE thread_id = $1 AND version < $2 \
193 ORDER BY version DESC LIMIT $3",
194 )
195 .bind(thread_id.to_string())
196 .bind(before)
197 .bind(i64::try_from(limit).unwrap_or(i64::MAX)),
198 )
199 .await
200 }
201
202 async fn delete(&self, thread_id: &str) -> Result<()> {
203 sqlx::query("DELETE FROM adk_graph_checkpoints WHERE thread_id = $1")
204 .bind(thread_id)
205 .execute(&self.pool)
206 .await
207 .map_err(|e| storage_error(BACKEND, e))?;
208 Ok(())
209 }
210
211 async fn prune(&self, thread_id: &str, policy: &RetentionPolicy) -> Result<usize> {
212 let expired = policy.expired(&self.list(thread_id).await?);
213 if expired.is_empty() {
214 return Ok(0);
215 }
216 let result =
217 sqlx::query("DELETE FROM adk_graph_checkpoints WHERE thread_id = $1 AND id = ANY($2)")
218 .bind(thread_id)
219 .bind(&expired)
220 .execute(&self.pool)
221 .await
222 .map_err(|e| storage_error(BACKEND, e))?;
223 Ok(result.rows_affected() as usize)
224 }
225}