alibi-sqlx 0.8.0

SQLx integration for Alibi
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! Application-owned organization plugin tables. Models derive [`crate::SqlxModel`]
//! and use Rust names for plugin fields, with `sqlx(rename)` for physical names.

use crate::model::{self, ActiveRow, SqlxModel};
use crate::pool::Exec;
use crate::sql::Sql;
use crate::store::entities::{invitation, member, organization};
use crate::value::{ColumnKind, SqlValue};
use alibi_core::field_policy::FieldValues;
use alibi_core::{AuthError, AuthResult, Invitation, Member, Organization};
use async_trait::async_trait;
use std::{marker::PhantomData, sync::Arc};

/// Bind the three organization entities to application models and ID factories.
/// This affects every plugin operation, including invitation transactions.
#[derive(Clone)]
pub struct OrganizationModels {
    pub(crate) organization: Binding<organization::Model>,
    pub(crate) member: Binding<member::Model>,
    pub(crate) invitation: Binding<invitation::Model>,
}

impl OrganizationModels {
    /// Models must declare the plugin's Rust field names. `updated_at` on the
    /// organization and `team_id` on the invitation may be omitted. Additional
    /// organization fields are retained and returned by the plugin.
    #[must_use]
    pub fn new<O: SqlxModel, M: SqlxModel, I: SqlxModel>(
        organization_id: fn() -> String,
        member_id: fn() -> String,
        invitation_id: fn() -> String,
    ) -> Self {
        Self {
            organization: Binding::new::<O>(organization_id),
            member: Binding::new::<M>(member_id),
            invitation: Binding::new::<I>(invitation_id),
        }
    }
}

impl Default for OrganizationModels {
    fn default() -> Self {
        fn id() -> String {
            uuid::Uuid::new_v4().to_string()
        }
        Self::new::<organization::Model, member::Model, invitation::Model>(id, id, id)
    }
}

#[async_trait]
trait Backend: Send + Sync {
    fn table(&self) -> &'static str;
    fn columns(&self) -> &'static [&'static str];
    fn fields(&self) -> &'static [(&'static str, &'static str)];
    fn kind(&self, physical: &str) -> ColumnKind;
    async fn fetch(&self, exec: Exec<'_>, sql: Sql) -> AuthResult<Vec<ActiveRow>>;
    async fn insert(&self, exec: Exec<'_>, row: &ActiveRow) -> AuthResult<ActiveRow>;
    async fn update(&self, exec: Exec<'_>, row: &ActiveRow) -> AuthResult<Option<ActiveRow>>;
}
struct TypedBackend<M>(PhantomData<M>);
#[async_trait]
impl<M: SqlxModel> Backend for TypedBackend<M> {
    fn table(&self) -> &'static str {
        M::TABLE
    }
    fn columns(&self) -> &'static [&'static str] {
        M::COLUMN_NAMES
    }
    fn fields(&self) -> &'static [(&'static str, &'static str)] {
        M::FIELD_COLUMNS
    }
    fn kind(&self, physical: &str) -> ColumnKind {
        M::column_kind(physical)
    }
    async fn fetch(&self, exec: Exec<'_>, sql: Sql) -> AuthResult<Vec<ActiveRow>> {
        Ok(exec
            .fetch_all::<M>(sql)
            .await?
            .into_iter()
            .map(SqlxModel::into_active)
            .collect())
    }
    async fn insert(&self, exec: Exec<'_>, row: &ActiveRow) -> AuthResult<ActiveRow> {
        Ok(model::insert::<M>(exec, row).await?.into_active())
    }
    async fn update(&self, exec: Exec<'_>, row: &ActiveRow) -> AuthResult<Option<ActiveRow>> {
        Ok(model::update::<M>(exec, row)
            .await?
            .map(SqlxModel::into_active))
    }
}

#[derive(Clone)]
pub(crate) struct Binding<T> {
    backend: Arc<dyn Backend>,
    generate_id: fn() -> String,
    _canonical: PhantomData<T>,
}

/// Canonical plugin fields and the original loaded write state. Keeping that
/// state prevents an update from overwriting unrelated application columns.
pub(crate) struct Row<T> {
    value: T,
    active: ActiveRow,
}
impl<T> std::ops::Deref for Row<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.value
    }
}
impl<T> Row<T> {
    pub(crate) fn active_role(&self) -> SqlValue {
        self.active
            .get("role")
            .and_then(crate::ActiveValue::value)
            .cloned()
            .unwrap_or(SqlValue::Text(None))
    }
    pub(crate) fn into_active(self) -> ActiveRow {
        self.active
    }
}

impl<T: SqlxModel> Binding<T> {
    fn new<M: SqlxModel>(generate_id: fn() -> String) -> Self {
        Self {
            backend: Arc::new(TypedBackend::<M>(PhantomData)),
            generate_id,
            _canonical: PhantomData,
        }
    }
    pub(crate) async fn set_fields(
        &self,
        exec: Exec<'_>,
        active: &mut ActiveRow,
        fields: &mut FieldValues,
    ) -> AuthResult<()> {
        fields.apply_adapter_transforms_async().await?;
        for (name, value) in &*fields {
            let requested = fields.binding_name(name);
            let column = self.physical(requested).ok_or_else(|| {
                AuthError::config(format!(
                    "configured organization field {name} has no model column"
                ))
            })?;
            let field = self.logical(column);
            if T::COLUMN_NAMES.contains(&field) {
                return Err(AuthError::config(
                    "additional organization fields cannot overwrite plugin fields",
                ));
            }
            let value = crate::additional_fields::prepare_value(
                exec,
                self.backend.kind(column),
                crate::additional_fields::raw_value(value)?,
            )
            .await?;
            active.set(field, value);
        }
        Ok(())
    }
    pub(crate) fn new_id(&self) -> String {
        (self.generate_id)()
    }
    pub(crate) fn table(&self) -> &'static str {
        self.backend.table()
    }
    pub(crate) fn physical(&self, field: &str) -> Option<&'static str> {
        self.backend
            .fields()
            .iter()
            .find(|(logical, _)| *logical == field)
            .map(|(_, physical)| *physical)
            .or_else(|| {
                self.backend
                    .columns()
                    .iter()
                    .copied()
                    .find(|column| *column == field)
            })
    }
    fn logical(&self, physical: &'static str) -> &'static str {
        self.backend
            .fields()
            .iter()
            .find(|(_, column)| *column == physical)
            .map_or(physical, |(logical, _)| *logical)
    }
    fn value(&self, field: &str, value: SqlValue) -> AuthResult<SqlValue> {
        let column = self.physical(field).ok_or_else(|| {
            AuthError::internal(format!("organization model has no {field} column"))
        })?;
        Ok(match (self.backend.kind(column), value) {
            (ColumnKind::BpChar, SqlValue::Text(value)) => SqlValue::BpChar(value),
            (ColumnKind::NaiveTimestamp, SqlValue::Timestamp(value)) => {
                SqlValue::NaiveTimestamp(value.map(|time| time.naive_utc()))
            }
            (ColumnKind::Text, SqlValue::Json(value)) => SqlValue::Text(
                value
                    .map(|value| alibi_core::utils::json::to_string(&*value))
                    .transpose()?,
            ),
            (_, value) => value,
        })
    }
    fn stage(&self, active: &ActiveRow) -> AuthResult<ActiveRow> {
        let mut physical = ActiveRow::new();
        for (field, value) in active.present() {
            let Some(column) = self.physical(field) else {
                if field == "updated_at" || (field == "team_id" && value.is_null()) {
                    continue;
                }
                return Err(AuthError::internal(format!(
                    "organization model has no {field} column"
                )));
            };
            let value = self.value(field, value.clone())?;
            if active.get(field).is_some_and(crate::ActiveValue::is_set) {
                physical.set(column, value);
            } else {
                physical.unchanged(column, value);
            }
        }
        Ok(physical)
    }
    fn row(&self, physical: &ActiveRow) -> AuthResult<Row<T>> {
        let mut active = ActiveRow::new();
        for (column, value) in physical.present() {
            let field = self.logical(column);
            let value = match value.clone() {
                SqlValue::NaiveTimestamp(value) => {
                    SqlValue::Timestamp(value.map(|time| time.and_utc()))
                }
                SqlValue::BpChar(value) => SqlValue::Text(value),
                value => value,
            };
            active.unchanged(field, value);
        }
        let mut canonical = active.clone();
        if T::TABLE == organization::Model::TABLE {
            if self.physical("updated_at").is_none()
                && let Some(time) = active.get("created_at").and_then(crate::ActiveValue::value)
            {
                canonical.unchanged("updated_at", time.clone());
            }
            if canonical
                .get("metadata")
                .and_then(crate::ActiveValue::value)
                .is_some_and(SqlValue::is_null)
            {
                canonical.unchanged("metadata", SqlValue::Json(None));
            }
        }
        if T::TABLE == invitation::Model::TABLE && self.physical("team_id").is_none() {
            canonical.unchanged("team_id", None::<String>);
        }
        let mut model = ActiveRow::new();
        for (logical, physical) in T::FIELD_COLUMNS {
            if let Some(value) = canonical.get(logical).and_then(crate::ActiveValue::value) {
                model.unchanged(physical, value.clone());
            }
        }
        Ok(Row {
            value: T::from_active(model)?,
            active,
        })
    }
    pub(crate) fn select(&self, exec: Exec<'_>) -> Sql {
        crate::sql::select(exec.engine(), self.table(), self.backend.columns())
    }
    pub(crate) fn by_id(&self, exec: Exec<'_>, id: impl Into<SqlValue>) -> AuthResult<Sql> {
        let mut sql = self.select(exec);
        sql.push(" WHERE ");
        self.compare(&mut sql, "id", " = ", id)?;
        Ok(sql)
    }
    pub(crate) fn delete_for_organization(&self, exec: Exec<'_>, id: &str) -> AuthResult<Sql> {
        let mut sql = Sql::with(exec.engine(), "DELETE FROM ");
        sql.ident(self.table());
        sql.push(" WHERE ");
        self.compare(&mut sql, "organization_id", " = ", id)?;
        Ok(sql)
    }
    pub(crate) fn delete_by_id(&self, exec: Exec<'_>, id: impl Into<SqlValue>) -> AuthResult<Sql> {
        let mut sql = Sql::with(exec.engine(), "DELETE FROM ");
        sql.ident(self.table());
        sql.push(" WHERE ");
        self.compare(&mut sql, "id", " = ", id)?;
        Ok(sql)
    }
    pub(crate) fn column(&self, sql: &mut Sql, field: &str) -> AuthResult<()> {
        let column = self.physical(field).ok_or_else(|| {
            AuthError::internal(format!("organization model has no {field} column"))
        })?;
        sql.column(self.table(), column);
        Ok(())
    }
    pub(crate) fn compare(
        &self,
        sql: &mut Sql,
        field: &str,
        operator: &str,
        value: impl Into<SqlValue>,
    ) -> AuthResult<()> {
        self.column(sql, field)?;
        sql.push(operator);
        sql.bind(self.value(field, value.into())?);
        Ok(())
    }
    pub(crate) fn assign(
        &self,
        sql: &mut Sql,
        field: &str,
        value: impl Into<SqlValue>,
    ) -> AuthResult<()> {
        let column = self.physical(field).ok_or_else(|| {
            AuthError::internal(format!("organization model has no {field} column"))
        })?;
        sql.assign(column, self.value(field, value.into())?);
        Ok(())
    }
    pub(crate) fn bind_list<I: IntoIterator<Item = String>>(
        &self,
        sql: &mut Sql,
        field: &str,
        values: I,
    ) -> AuthResult<()> {
        sql.bind_list(
            values
                .into_iter()
                .map(|value| self.value(field, value.into()))
                .collect::<AuthResult<Vec<_>>>()?,
        );
        Ok(())
    }
    pub(crate) fn returning(&self, sql: &mut Sql) {
        sql.push(" RETURNING ");
        sql.column_list(self.backend.columns());
    }
    pub(crate) async fn fetch_all(&self, exec: Exec<'_>, sql: Sql) -> AuthResult<Vec<Row<T>>> {
        self.backend
            .fetch(exec, sql)
            .await?
            .into_iter()
            .map(|active| self.row(&active))
            .collect()
    }
    pub(crate) async fn fetch_optional(
        &self,
        exec: Exec<'_>,
        sql: Sql,
    ) -> AuthResult<Option<Row<T>>> {
        Ok(self.fetch_all(exec, sql).await?.into_iter().next())
    }
    pub(crate) async fn insert(&self, exec: Exec<'_>, active: &ActiveRow) -> AuthResult<Row<T>> {
        self.row(&self.backend.insert(exec, &self.stage(active)?).await?)
    }
    pub(crate) async fn update(
        &self,
        exec: Exec<'_>,
        active: &ActiveRow,
    ) -> AuthResult<Option<Row<T>>> {
        self.backend
            .update(exec, &self.stage(active)?)
            .await?
            .map(|active| self.row(&active))
            .transpose()
    }
}

impl From<&Row<organization::Model>> for Organization {
    fn from(row: &Row<organization::Model>) -> Self {
        let mut organization = Self::from(&row.value);
        for (field, value) in row.active.present() {
            if organization::Model::COLUMN_NAMES.contains(&field) {
                continue;
            }
            if let Some(value) = output_value(value) {
                _ = organization
                    .additional_fields
                    .insert(field.to_owned(), value);
            }
        }
        organization
    }
}
impl From<&Row<member::Model>> for Member {
    fn from(row: &Row<member::Model>) -> Self {
        Self::from(&row.value)
    }
}
impl From<&Row<invitation::Model>> for Invitation {
    fn from(row: &Row<invitation::Model>) -> Self {
        let mut invitation = Self::from(&row.value);
        if row
            .active
            .get("role")
            .and_then(crate::ActiveValue::value)
            .is_some_and(SqlValue::is_null)
        {
            invitation.role = None;
        }
        invitation
    }
}

fn output_value(value: &SqlValue) -> Option<serde_json::Value> {
    if value.is_null() {
        return Some(serde_json::Value::Null);
    }
    match value {
        SqlValue::Text(Some(value)) | SqlValue::BpChar(Some(value)) => Some(value.clone().into()),
        SqlValue::Bool(Some(value)) => Some((*value).into()),
        SqlValue::Int(Some(value)) => Some((*value).into()),
        SqlValue::BigInt(Some(value)) => Some((*value).into()),
        SqlValue::Float(Some(value)) => {
            serde_json::Number::from_f64(f64::from(*value)).map(Into::into)
        }
        SqlValue::Double(Some(value)) => serde_json::Number::from_f64(*value).map(Into::into),
        SqlValue::Json(Some(value)) => Some((**value).clone()),
        _ => None,
    }
}