2025-07-08 16:54:51 -07:00
|
|
|
use chrono::{DateTime, Utc};
|
2025-07-18 16:20:03 -07:00
|
|
|
use derive_builder::Builder;
|
2025-07-08 16:54:51 -07:00
|
|
|
use interim_pgtypes::pg_attribute::PgAttribute;
|
|
|
|
|
use serde::{Deserialize, Serialize};
|
2025-08-04 13:59:42 -07:00
|
|
|
use sqlx::{Decode, Postgres, Row as _, TypeInfo as _, ValueRef as _, postgres::PgRow, query_as};
|
2025-07-08 16:54:51 -07:00
|
|
|
use thiserror::Error;
|
|
|
|
|
use uuid::Uuid;
|
|
|
|
|
|
2025-08-04 13:59:42 -07:00
|
|
|
use crate::client::AppDbClient;
|
|
|
|
|
|
2025-07-18 16:20:03 -07:00
|
|
|
pub const RFC_3339_S: &str = "%Y-%m-%dT%H:%M:%S";
|
2025-07-08 16:54:51 -07:00
|
|
|
|
|
|
|
|
#[derive(Clone, Debug, Deserialize, Serialize)]
|
|
|
|
|
pub struct Field {
|
2025-07-18 16:20:03 -07:00
|
|
|
pub id: Uuid,
|
2025-07-08 16:54:51 -07:00
|
|
|
pub name: String,
|
|
|
|
|
pub label: Option<String>,
|
|
|
|
|
pub field_type: sqlx::types::Json<FieldType>,
|
|
|
|
|
pub width_px: i32,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Field {
|
2025-07-18 16:20:03 -07:00
|
|
|
pub fn insertable_builder() -> InsertableFieldBuilder {
|
|
|
|
|
InsertableFieldBuilder::default()
|
|
|
|
|
}
|
|
|
|
|
|
2025-07-08 16:54:51 -07:00
|
|
|
pub fn default_from_attr(attr: &PgAttribute) -> Self {
|
|
|
|
|
Self {
|
2025-07-18 16:20:03 -07:00
|
|
|
id: Uuid::now_v7(),
|
2025-07-08 16:54:51 -07:00
|
|
|
name: attr.attname.clone(),
|
|
|
|
|
label: None,
|
|
|
|
|
field_type: sqlx::types::Json(FieldType::default_from_attr(attr)),
|
|
|
|
|
width_px: 200,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn webc_tag(&self) -> &str {
|
|
|
|
|
match self.field_type.0 {
|
2025-08-10 14:32:15 -07:00
|
|
|
FieldType::InterimUser {} => "cell-interim-user",
|
|
|
|
|
FieldType::Text {} => "cell-text",
|
2025-07-08 16:54:51 -07:00
|
|
|
FieldType::Timestamp { .. } => "cell-timestamp",
|
2025-08-24 23:24:01 -07:00
|
|
|
FieldType::Uuid {} => "cell-uuid",
|
2025-07-08 16:54:51 -07:00
|
|
|
FieldType::Unknown => "cell-unknown",
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn webc_custom_attrs(&self) -> Vec<(String, String)> {
|
2025-08-24 23:24:01 -07:00
|
|
|
vec![]
|
2025-07-08 16:54:51 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn get_value_encodable(&self, row: &PgRow) -> Result<Encodable, ParseError> {
|
|
|
|
|
let value_ref = row
|
|
|
|
|
.try_get_raw(self.name.as_str())
|
|
|
|
|
.or(Err(ParseError::FieldNotFound))?;
|
|
|
|
|
let type_info = value_ref.type_info();
|
|
|
|
|
let ty = type_info.name();
|
|
|
|
|
Ok(match ty {
|
|
|
|
|
"TEXT" | "VARCHAR" => {
|
|
|
|
|
Encodable::Text(<Option<String> as Decode<Postgres>>::decode(value_ref).unwrap())
|
|
|
|
|
}
|
|
|
|
|
"UUID" => {
|
|
|
|
|
Encodable::Uuid(<Option<Uuid> as Decode<Postgres>>::decode(value_ref).unwrap())
|
|
|
|
|
}
|
|
|
|
|
_ => return Err(ParseError::UnknownType),
|
|
|
|
|
})
|
|
|
|
|
}
|
2025-08-04 13:59:42 -07:00
|
|
|
|
|
|
|
|
pub fn belonging_to_lens(lens_id: Uuid) -> BelongingToLensQuery {
|
|
|
|
|
BelongingToLensQuery { lens_id }
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
|
pub struct BelongingToLensQuery {
|
|
|
|
|
lens_id: Uuid,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl BelongingToLensQuery {
|
|
|
|
|
pub async fn fetch_all(self, app_db: &mut AppDbClient) -> Result<Vec<Field>, sqlx::Error> {
|
|
|
|
|
query_as!(
|
|
|
|
|
Field,
|
|
|
|
|
r#"
|
|
|
|
|
select
|
|
|
|
|
id,
|
|
|
|
|
name,
|
|
|
|
|
label,
|
|
|
|
|
field_type as "field_type: sqlx::types::Json<FieldType>",
|
|
|
|
|
width_px
|
|
|
|
|
from fields
|
|
|
|
|
where lens_id = $1
|
|
|
|
|
"#,
|
|
|
|
|
self.lens_id
|
|
|
|
|
)
|
|
|
|
|
.fetch_all(&mut *app_db.conn)
|
|
|
|
|
.await
|
|
|
|
|
}
|
2025-07-08 16:54:51 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Clone, Debug, Deserialize, Serialize)]
|
|
|
|
|
#[serde(tag = "t", content = "c")]
|
|
|
|
|
pub enum FieldType {
|
2025-08-10 14:32:15 -07:00
|
|
|
InterimUser {},
|
|
|
|
|
Text {},
|
2025-07-08 16:54:51 -07:00
|
|
|
Timestamp {
|
|
|
|
|
format: String,
|
|
|
|
|
},
|
2025-08-24 23:24:01 -07:00
|
|
|
Uuid {},
|
2025-07-08 16:54:51 -07:00
|
|
|
/// A special variant for when the field type is not specified and cannot be
|
|
|
|
|
/// inferred. This isn't represented as an error, because we still want to
|
|
|
|
|
/// be able to define display behavior via the .render() method.
|
|
|
|
|
Unknown,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl FieldType {
|
|
|
|
|
pub fn default_from_attr(attr: &PgAttribute) -> Self {
|
|
|
|
|
match attr.regtype.as_str() {
|
2025-08-10 14:32:15 -07:00
|
|
|
"text" => Self::Text {},
|
2025-07-08 16:54:51 -07:00
|
|
|
"timestamp" => Self::Timestamp {
|
|
|
|
|
format: RFC_3339_S.to_owned(),
|
|
|
|
|
},
|
2025-08-24 23:24:01 -07:00
|
|
|
"uuid" => Self::Uuid {},
|
2025-07-08 16:54:51 -07:00
|
|
|
_ => Self::Unknown,
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-07-18 16:20:03 -07:00
|
|
|
|
|
|
|
|
/// Returns a SQL fragment for the default data type for creating or
|
|
|
|
|
/// altering a backing column, such as "integer", or "timestamptz". Returns
|
|
|
|
|
/// None if the field type is Unknown.
|
|
|
|
|
pub fn attr_data_type_fragment(&self) -> Option<&'static str> {
|
|
|
|
|
match self {
|
2025-08-10 14:32:15 -07:00
|
|
|
Self::InterimUser {} | Self::Text {} => Some("text"),
|
2025-07-18 16:20:03 -07:00
|
|
|
Self::Timestamp { .. } => Some("timestamptz"),
|
2025-08-10 14:32:15 -07:00
|
|
|
Self::Uuid { .. } => Some("uuid"),
|
2025-07-18 16:20:03 -07:00
|
|
|
Self::Unknown => None,
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-07-08 16:54:51 -07:00
|
|
|
}
|
|
|
|
|
|
2025-08-10 14:32:15 -07:00
|
|
|
#[derive(Clone, Debug, Error)]
|
|
|
|
|
#[error("field type is unknown")]
|
|
|
|
|
pub struct FieldTypeUnknownError {}
|
|
|
|
|
|
2025-07-18 16:20:03 -07:00
|
|
|
// -------- Insertable --------
|
|
|
|
|
|
|
|
|
|
#[derive(Builder, Clone, Debug)]
|
|
|
|
|
pub struct InsertableField {
|
|
|
|
|
lens_id: Uuid,
|
|
|
|
|
name: String,
|
|
|
|
|
#[builder(default)]
|
|
|
|
|
label: Option<String>,
|
|
|
|
|
field_type: FieldType,
|
|
|
|
|
#[builder(default = 200)]
|
|
|
|
|
width_px: i32,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl InsertableField {
|
2025-08-04 13:59:42 -07:00
|
|
|
pub async fn insert(self, app_db: &mut AppDbClient) -> Result<Field, sqlx::Error> {
|
2025-07-18 16:20:03 -07:00
|
|
|
query_as!(
|
|
|
|
|
Field,
|
|
|
|
|
r#"
|
|
|
|
|
insert into fields
|
|
|
|
|
(id, lens_id, name, label, field_type, width_px)
|
|
|
|
|
values ($1, $2, $3, $4, $5, $6)
|
|
|
|
|
returning
|
|
|
|
|
id,
|
|
|
|
|
name,
|
|
|
|
|
label,
|
|
|
|
|
field_type as "field_type: sqlx::types::Json<FieldType>",
|
|
|
|
|
width_px
|
|
|
|
|
"#,
|
|
|
|
|
Uuid::now_v7(),
|
|
|
|
|
self.lens_id,
|
|
|
|
|
self.name,
|
|
|
|
|
self.label,
|
|
|
|
|
sqlx::types::Json::<_>(self.field_type) as sqlx::types::Json<FieldType>,
|
|
|
|
|
self.width_px,
|
|
|
|
|
)
|
2025-08-04 13:59:42 -07:00
|
|
|
.fetch_one(&mut *app_db.conn)
|
2025-07-18 16:20:03 -07:00
|
|
|
.await
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl InsertableFieldBuilder {
|
|
|
|
|
pub fn default_from_attr(attr: &PgAttribute) -> Self {
|
|
|
|
|
Self {
|
|
|
|
|
name: Some(attr.attname.clone()),
|
|
|
|
|
field_type: Some(FieldType::default_from_attr(attr)),
|
|
|
|
|
..Self::default()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// -------- Errors --------
|
|
|
|
|
|
2025-07-08 16:54:51 -07:00
|
|
|
/// Error when parsing a sqlx value to JSON
|
|
|
|
|
#[derive(Debug, Error)]
|
|
|
|
|
pub enum ParseError {
|
|
|
|
|
#[error("incompatible json type")]
|
|
|
|
|
BadJsonType,
|
|
|
|
|
#[error("field not found in row")]
|
|
|
|
|
FieldNotFound,
|
|
|
|
|
#[error("unknown postgres type")]
|
|
|
|
|
UnknownType,
|
|
|
|
|
}
|
|
|
|
|
|
2025-07-18 16:20:03 -07:00
|
|
|
// -------- Encodable --------
|
|
|
|
|
// TODO this should probably be moved to another crate
|
|
|
|
|
|
2025-07-08 16:54:51 -07:00
|
|
|
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
|
|
|
|
#[serde(tag = "t", content = "c")]
|
|
|
|
|
pub enum Encodable {
|
|
|
|
|
Text(Option<String>),
|
2025-08-10 14:32:15 -07:00
|
|
|
Timestamp(Option<DateTime<Utc>>),
|
2025-07-08 16:54:51 -07:00
|
|
|
Uuid(Option<Uuid>),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Encodable {
|
|
|
|
|
pub fn bind_onto<'a>(
|
2025-08-13 18:52:37 -07:00
|
|
|
self,
|
2025-07-08 16:54:51 -07:00
|
|
|
query: sqlx::query::Query<'a, Postgres, <sqlx::Postgres as sqlx::Database>::Arguments<'a>>,
|
|
|
|
|
) -> sqlx::query::Query<'a, Postgres, <sqlx::Postgres as sqlx::Database>::Arguments<'a>> {
|
|
|
|
|
match self {
|
|
|
|
|
Self::Text(value) => query.bind(value),
|
2025-08-10 14:32:15 -07:00
|
|
|
Self::Timestamp(value) => query.bind(value),
|
2025-07-08 16:54:51 -07:00
|
|
|
Self::Uuid(value) => query.bind(value),
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-07-25 15:01:31 -07:00
|
|
|
|
|
|
|
|
/// Transform the contained value into a serde_json::Value.
|
|
|
|
|
pub fn inner_as_value(&self) -> serde_json::Value {
|
|
|
|
|
let serialized = serde_json::to_value(self).unwrap();
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
|
struct Tagged {
|
|
|
|
|
c: serde_json::Value,
|
|
|
|
|
}
|
|
|
|
|
let deserialized: Tagged = serde_json::from_value(serialized).unwrap();
|
|
|
|
|
deserialized.c
|
|
|
|
|
}
|
2025-08-13 18:52:37 -07:00
|
|
|
|
|
|
|
|
pub fn is_none(&self) -> bool {
|
|
|
|
|
match self {
|
|
|
|
|
Self::Text(None) | Self::Timestamp(None) | Self::Uuid(None) => true,
|
|
|
|
|
Self::Text(_) | Self::Timestamp(_) | Self::Uuid(_) => false,
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-07-08 16:54:51 -07:00
|
|
|
}
|