1use crate::table_name;
12use ojak::kv::{KvError, KvStore};
13use serde_json::Value;
14use sqlx::PgPool;
15use std::time::Duration;
16
17#[derive(Clone, Debug)]
19pub struct PostgresKvStore {
20 pool: PgPool,
21 table: String,
22}
23
24impl PostgresKvStore {
25 #[must_use]
27 pub fn new(pool: PgPool) -> Self {
28 Self {
29 pool,
30 table: "ojak_kv".to_owned(),
31 }
32 }
33
34 pub fn with_table(pool: PgPool, table: &str) -> Result<Self, KvError> {
40 Ok(Self {
41 pool,
42 table: table_name(table).map_err(KvError)?,
43 })
44 }
45
46 pub async fn initialize(&self) -> Result<(), KvError> {
53 for statement in Self::schema(&self.table) {
54 sqlx::query(crate::sql(statement))
55 .execute(&self.pool)
56 .await
57 .map_err(error)?;
58 }
59 Ok(())
60 }
61
62 #[must_use]
66 pub fn schema(table: &str) -> Vec<String> {
67 let index = format!("{}_expires", table.replace('.', "_"));
68 vec![
69 format!(
70 "CREATE TABLE IF NOT EXISTS {table} (
71 key TEXT PRIMARY KEY,
72 value TEXT NOT NULL,
73 expires_at TIMESTAMPTZ
74 )"
75 ),
76 format!(
77 "CREATE INDEX IF NOT EXISTS {index} ON {table} (expires_at) \
78 WHERE expires_at IS NOT NULL"
79 ),
80 ]
81 }
82
83 pub async fn prune_expired(&self) -> Result<u64, KvError> {
89 let result = sqlx::query(crate::sql(format!(
90 "DELETE FROM {} WHERE expires_at <= now()",
91 self.table
92 )))
93 .execute(&self.pool)
94 .await
95 .map_err(error)?;
96 Ok(result.rows_affected())
97 }
98}
99
100fn error(error: sqlx::Error) -> KvError {
101 KvError(error.to_string())
102}
103
104fn encode_key(key: &[&str]) -> Result<String, KvError> {
105 serde_json::to_string(key).map_err(|error| KvError(error.to_string()))
106}
107
108fn encode_value(value: &Value) -> Result<String, KvError> {
109 serde_json::to_string(value).map_err(|error| KvError(error.to_string()))
110}
111
112fn seconds(ttl: Option<Duration>) -> Option<f64> {
113 ttl.map(|ttl| ttl.as_secs_f64())
114}
115
116const EXPIRES: &str = "CASE WHEN $3::float8 IS NULL THEN NULL \
118 ELSE now() + make_interval(secs => $3::float8) END";
119
120impl KvStore for PostgresKvStore {
121 async fn get(&self, key: &[&str]) -> Result<Option<Value>, KvError> {
122 let value: Option<String> = sqlx::query_scalar(crate::sql(format!(
123 "SELECT value FROM {} WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())",
124 self.table
125 )))
126 .bind(encode_key(key)?)
127 .fetch_optional(&self.pool)
128 .await
129 .map_err(error)?;
130 value
131 .map(|value| serde_json::from_str(&value).map_err(|error| KvError(error.to_string())))
132 .transpose()
133 }
134
135 async fn set(&self, key: &[&str], value: Value, ttl: Option<Duration>) -> Result<(), KvError> {
136 sqlx::query(crate::sql(format!(
137 "INSERT INTO {} (key, value, expires_at) VALUES ($1, $2, {EXPIRES})
138 ON CONFLICT (key) DO UPDATE
139 SET value = EXCLUDED.value, expires_at = EXCLUDED.expires_at",
140 self.table
141 )))
142 .bind(encode_key(key)?)
143 .bind(encode_value(&value)?)
144 .bind(seconds(ttl))
145 .execute(&self.pool)
146 .await
147 .map_err(error)?;
148 Ok(())
149 }
150
151 async fn insert(
152 &self,
153 key: &[&str],
154 value: Value,
155 ttl: Option<Duration>,
156 ) -> Result<bool, KvError> {
157 let table = &self.table;
160 let put: Option<i32> = sqlx::query_scalar(crate::sql(format!(
161 "INSERT INTO {table} (key, value, expires_at) VALUES ($1, $2, {EXPIRES})
162 ON CONFLICT (key) DO UPDATE
163 SET value = EXCLUDED.value, expires_at = EXCLUDED.expires_at
164 WHERE {table}.expires_at <= now()
165 RETURNING 1"
166 )))
167 .bind(encode_key(key)?)
168 .bind(encode_value(&value)?)
169 .bind(seconds(ttl))
170 .fetch_optional(&self.pool)
171 .await
172 .map_err(error)?;
173 Ok(put.is_some())
174 }
175
176 async fn delete(&self, key: &[&str]) -> Result<(), KvError> {
177 sqlx::query(crate::sql(format!(
178 "DELETE FROM {} WHERE key = $1",
179 self.table
180 )))
181 .bind(encode_key(key)?)
182 .execute(&self.pool)
183 .await
184 .map_err(error)?;
185 Ok(())
186 }
187}