1mod migrate;
11#[cfg(feature = "mysql")]
12mod mysql;
13mod options;
14#[cfg(feature = "sqlite")]
15mod sqlite;
16
17pub use migrate::{MigrateError, MigrateReport, Migration};
18#[cfg(feature = "mysql")]
19pub use mysql::{MysqlBackend, MysqlTx};
20pub use options::{ConnectOptions, TlsPolicy};
21#[cfg(feature = "sqlite")]
22pub use sqlite::{SqliteBackend, SqliteTx};
23
24use persistant_relational::{Dialect, RelError, RelationalBackend, RelationalTx, Row, Value};
25use sqlx::postgres::{PgArguments, PgPoolOptions, PgRow};
26use sqlx::query::Query;
27use sqlx::{Column, Postgres, Row as SqlxRow, TypeInfo, ValueRef};
28
29pub(crate) fn classify(e: sqlx::Error) -> RelError {
31 match &e {
32 sqlx::Error::Database(db) => {
33 let constraint = db.constraint().map(str::to_string);
34 match db.code().as_deref() {
35 Some("23505") => RelError::UniqueViolation { constraint },
36 Some("23503") => RelError::ForeignKeyViolation { constraint },
37 Some("23514") | Some("23502") => RelError::CheckViolation { constraint },
38 Some("40001") => RelError::Serialization,
39 Some("40P01") => RelError::Deadlock,
40 Some(c) if c.starts_with("08") || c.starts_with("57P") => {
41 RelError::Unavailable(e.to_string())
42 }
43 _ => RelError::Backend(e.to_string()),
44 }
45 }
46 sqlx::Error::Io(_) | sqlx::Error::PoolTimedOut | sqlx::Error::PoolClosed => {
47 RelError::Unavailable(e.to_string())
48 }
49 _ => RelError::Backend(e.to_string()),
50 }
51}
52
53fn bind<'q>(
54 mut q: Query<'q, Postgres, PgArguments>,
55 params: &'q [Value],
56) -> Result<Query<'q, Postgres, PgArguments>, RelError> {
57 for p in params {
58 q = match p {
59 Value::Null => q.bind(Option::<String>::None),
62 Value::Bool(b) => q.bind(*b),
63 Value::Int(n) => q.bind(*n),
64 Value::Float(f) => q.bind(*f),
65 Value::Text(s) => q.bind(s.as_str()),
66 Value::Bytes(b) => q.bind(b.as_slice()),
67 other => {
68 return Err(RelError::Unsupported(format!(
69 "parameter {other:?} has no PostgreSQL binding in this driver"
70 )));
71 }
72 };
73 }
74 Ok(q)
75}
76
77fn decode(row: &PgRow) -> Result<Row, RelError> {
78 let mut values = Vec::with_capacity(row.columns().len());
79 for (i, col) in row.columns().iter().enumerate() {
80 let raw = row.try_get_raw(i).map_err(classify)?;
81 if raw.is_null() {
82 values.push(Value::Null);
83 continue;
84 }
85 let name = col.type_info().name().to_string();
86 let v = match name.as_str() {
87 "BOOL" => Value::Bool(row.try_get::<bool, _>(i).map_err(classify)?),
88 "INT2" => Value::Int(i64::from(row.try_get::<i16, _>(i).map_err(classify)?)),
89 "INT4" => Value::Int(i64::from(row.try_get::<i32, _>(i).map_err(classify)?)),
90 "INT8" => Value::Int(row.try_get::<i64, _>(i).map_err(classify)?),
91 "FLOAT4" => Value::Float(f64::from(row.try_get::<f32, _>(i).map_err(classify)?)),
92 "FLOAT8" => Value::Float(row.try_get::<f64, _>(i).map_err(classify)?),
93 "TEXT" | "VARCHAR" | "NAME" | "BPCHAR" => {
94 Value::Text(row.try_get::<String, _>(i).map_err(classify)?)
95 }
96 "BYTEA" => Value::Bytes(row.try_get::<Vec<u8>, _>(i).map_err(classify)?),
97 other => {
98 return Err(RelError::Unsupported(format!(
99 "column {:?} has type {other}, which Value cannot carry; use PgBackend::pool",
100 col.name()
101 )));
102 }
103 };
104 values.push(v);
105 }
106 Ok(Row::new(values))
107}
108
109#[derive(Debug, Clone)]
111pub struct PgBackend {
112 pool: sqlx::PgPool,
113 version: String,
114}
115
116impl PgBackend {
117 pub async fn connect(url: &str) -> Result<Self, RelError> {
121 let pool = PgPoolOptions::new()
122 .max_connections(16)
123 .connect(url)
124 .await
125 .map_err(classify)?;
126 Self::from_pool(pool).await
127 }
128
129 pub async fn connect_secret(
132 secret: &persistant_relational::ConnectionSecret,
133 ) -> Result<Self, RelError> {
134 let url = secret.resolve()?;
135 Self::connect(url.expose()).await
136 }
137
138 pub async fn from_pool(pool: sqlx::PgPool) -> Result<Self, RelError> {
140 let full: String = sqlx::query_scalar("SHOW server_version")
141 .fetch_one(&pool)
142 .await
143 .map_err(classify)?;
144 let version = full.split_whitespace().next().unwrap_or("").to_string();
146 Ok(PgBackend { pool, version })
147 }
148
149 pub fn pool(&self) -> &sqlx::PgPool {
151 &self.pool
152 }
153}
154
155impl RelationalBackend for PgBackend {
156 type Tx<'a> = PgTx<'a>;
157
158 fn backend(&self) -> &str {
159 "postgres"
160 }
161
162 fn version(&self) -> &str {
163 &self.version
164 }
165
166 fn dialect(&self) -> Dialect {
167 Dialect::Postgres
168 }
169
170 async fn execute(&self, sql: &str, params: &[Value]) -> Result<u64, RelError> {
171 let q = bind(sqlx::query(sqlx::AssertSqlSafe(sql.to_string())), params)?;
172 q.execute(&self.pool)
173 .await
174 .map(|r| r.rows_affected())
175 .map_err(classify)
176 }
177
178 async fn query(&self, sql: &str, params: &[Value]) -> Result<Vec<Row>, RelError> {
179 let q = bind(sqlx::query(sqlx::AssertSqlSafe(sql.to_string())), params)?;
180 let rows = q.fetch_all(&self.pool).await.map_err(classify)?;
181 rows.iter().map(decode).collect()
182 }
183
184 async fn begin(&self) -> Result<PgTx<'_>, RelError> {
185 Ok(PgTx {
186 tx: self.pool.begin().await.map_err(classify)?,
187 })
188 }
189}
190
191#[derive(Debug)]
193pub struct PgTx<'a> {
194 tx: sqlx::Transaction<'a, Postgres>,
195}
196
197impl RelationalTx for PgTx<'_> {
198 async fn execute(&mut self, sql: &str, params: &[Value]) -> Result<u64, RelError> {
199 let q = bind(sqlx::query(sqlx::AssertSqlSafe(sql.to_string())), params)?;
200 q.execute(&mut *self.tx)
201 .await
202 .map(|r| r.rows_affected())
203 .map_err(classify)
204 }
205
206 async fn query(&mut self, sql: &str, params: &[Value]) -> Result<Vec<Row>, RelError> {
207 let q = bind(sqlx::query(sqlx::AssertSqlSafe(sql.to_string())), params)?;
208 let rows = q.fetch_all(&mut *self.tx).await.map_err(classify)?;
209 rows.iter().map(decode).collect()
210 }
211
212 async fn commit(self) -> Result<(), RelError> {
213 self.tx.commit().await.map_err(classify)
214 }
215
216 async fn rollback(self) -> Result<(), RelError> {
217 self.tx.rollback().await.map_err(classify)
218 }
219}