1use std::fmt;
36use std::ops::{Bound, RangeBounds};
37use std::sync::atomic::{AtomicU64, Ordering};
38
39use super::cast::Cast;
40use super::query::Col;
41use super::sql::{Dialect, Sql};
42use super::value::{Timestamp, ToValue, Value};
43use super::{Connection, current_in};
44use crate::context::Params;
45use crate::error::{Error, Result};
46use crate::model::Model;
47
48static SAVEPOINTS: AtomicU64 = AtomicU64::new(0);
49
50#[derive(Debug)]
53pub enum Save<M> {
54 Saved(M),
55 Invalid(Changeset<M>),
56}
57
58impl<M: Model> Save<M> {
59 pub fn saved(self) -> Option<M> {
61 match self {
62 Save::Saved(record) => Some(record),
63 Save::Invalid(_) => None,
64 }
65 }
66
67 #[track_caller]
73 pub fn unwrap(self) -> M {
74 match self {
75 Save::Saved(record) => record,
76 Save::Invalid(changeset) => panic!(
77 "expected a saved record, but it was invalid: {:?}",
78 changeset.full_messages()
79 ),
80 }
81 }
82
83 #[track_caller]
89 pub fn unwrap_invalid(self) -> Changeset<M> {
90 match self {
91 Save::Invalid(changeset) => changeset,
92 Save::Saved(_) => panic!("expected validation errors, but the record was saved"),
93 }
94 }
95}
96
97impl<M: Model> From<Params> for Changeset<M> {
99 fn from(params: Params) -> Self {
100 let mut changeset = M::from_params(¶ms);
101 changeset.params = Some(Box::new(params));
104 changeset
105 }
106}
107
108pub struct Changeset<M> {
109 data: Option<M>,
110 changes: Vec<(&'static str, Value)>,
111 errors: Vec<(&'static str, String)>,
112 unique: Vec<&'static str>,
113 unique_scopes: Vec<(&'static str, Vec<&'static str>)>,
116 conn: Option<Connection>,
117 params: Option<Box<Params>>,
120}
121
122impl<M: Model> Default for Changeset<M> {
123 fn default() -> Self {
124 Self::new()
125 }
126}
127
128impl<M: fmt::Debug> fmt::Debug for Changeset<M> {
129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 f.debug_struct("Changeset")
131 .field("data", &self.data)
132 .field("changes", &self.changes)
133 .field("errors", &self.errors)
134 .finish()
135 }
136}
137
138impl<M: Model> Changeset<M> {
139 pub fn new() -> Self {
141 Self {
142 data: None,
143 changes: Vec::new(),
144 errors: Vec::new(),
145 unique: Vec::new(),
146 unique_scopes: Vec::new(),
147 conn: None,
148 params: None,
149 }
150 }
151
152 pub fn for_record(record: M) -> Self {
154 Self {
155 data: Some(record),
156 ..Self::new()
157 }
158 }
159
160 pub(crate) fn new_record(&self) -> Option<M> {
164 let mut record = M::blank()?;
165 if let Some(params) = &self.params {
166 record.assign(params);
167 }
168 for (column, value) in &self.changes {
169 record.set_value(column, value.clone());
170 }
171 Some(record)
172 }
173
174 pub(crate) fn take_record(&mut self) -> Option<(M, Vec<(&'static str, Value)>)> {
178 let mut record = self.data.take()?;
179 let held: Vec<(&'static str, Value)> = record
180 .values()
181 .into_iter()
182 .chain(record.attribute_values())
183 .collect();
184 let mut was = Vec::new();
185 if let Some(params) = &self.params {
186 for (column, value) in record.attribute_values() {
187 if params.get(column).is_some() {
188 was.push((column, value));
189 }
190 }
191 record.assign(params);
192 }
193 for (column, value) in &self.changes {
194 if let Some((name, old)) = held.iter().find(|(c, _)| c == column) {
195 was.push((*name, old.clone()));
196 }
197 record.set_value(column, value.clone());
198 }
199 Some((record, was))
200 }
201
202 pub(crate) fn changed_by(mut self, record: &M, before: &[(&'static str, Value)]) -> Self {
205 for (column, value) in record.values() {
206 let was = before.iter().find(|(c, _)| *c == column).map(|(_, v)| v);
207 if was != Some(&value) {
208 self = self.put(column, value);
209 }
210 }
211 self
212 }
213
214 pub(crate) fn data_mut(&mut self) -> Option<&mut M> {
215 self.data.as_mut()
216 }
217
218 pub(crate) fn take_data(&mut self) -> Option<M> {
219 self.data.take()
220 }
221
222 pub(crate) fn attach(mut self, record: M) -> Self {
223 self.data = Some(record);
224 self
225 }
226
227 pub(crate) fn put(mut self, column: &'static str, value: Value) -> Self {
229 self.changes.retain(|(n, _)| *n != column);
230 self.changes.push((column, value));
231 self
232 }
233
234 pub(crate) fn push_error(mut self, column: &'static str, message: String) -> Self {
235 self.errors.push((column, message));
236 self
237 }
238
239 pub fn set<T: ToValue>(
241 mut self,
242 column: impl FnOnce(&M::Columns) -> Col<M, T>,
243 value: impl Into<T>,
244 ) -> Self {
245 let name = column(&M::columns()).name();
246 let value = value.into().to_value();
247 self.changes.retain(|(n, _)| *n != name);
248 self.changes.push((name, value));
249 self
250 }
251
252 pub fn cast<T: Cast + ToValue>(
256 mut self,
257 column: impl FnOnce(&M::Columns) -> Col<M, T>,
258 params: &Params,
259 ) -> Self {
260 let name = column(&M::columns()).name();
261 if let Some(raw) = params.get(name) {
262 match T::cast(raw) {
263 Ok(value) => {
264 self.changes.retain(|(n, _)| *n != name);
265 self.changes.push((name, value.to_value()));
266 }
267 Err(message) => {
268 self.changes.retain(|(n, _)| *n != name);
270 self.changes.push((name, Value::Text(raw.to_owned())));
271 self.errors.push((name, message));
272 }
273 }
274 }
275 self
276 }
277
278 pub fn value(&self, column: &str) -> Option<Value> {
281 self.changes
282 .iter()
283 .find(|(n, _)| *n == column)
284 .map(|(_, v)| v.clone())
285 .or_else(|| {
286 let data = self.data.as_ref()?;
287 data.values()
288 .into_iter()
289 .find(|(n, _)| *n == column)
290 .map(|(_, v)| v)
291 })
292 }
293
294 pub fn text(&self, column: &str) -> String {
297 self.value(column).map(|v| v.to_text()).unwrap_or_default()
298 }
299
300 pub fn changes(&self) -> &[(&'static str, Value)] {
301 &self.changes
302 }
303
304 pub fn data(&self) -> Option<&M> {
305 self.data.as_ref()
306 }
307
308 pub(crate) fn without_errors(mut self) -> Self {
311 self.errors.clear();
312 self
313 }
314
315 pub fn is_valid(&self) -> bool {
316 self.errors.is_empty()
317 }
318
319 pub fn errors_json(&self) -> serde_json::Value {
321 crate::db::record::errors_json(&self.errors)
322 }
323
324 pub fn errors(&self) -> &[(&'static str, String)] {
325 &self.errors
326 }
327
328 pub fn field(&self, column: &str) -> crate::view::Field {
332 crate::view::Field::new(
333 column,
334 self.text(column),
335 self.errors_on(column)
336 .into_iter()
337 .map(str::to_owned)
338 .collect(),
339 )
340 }
341
342 pub fn errors_on(&self, column: &str) -> Vec<&str> {
343 self.errors
344 .iter()
345 .filter(|(n, _)| *n == column)
346 .map(|(_, m)| m.as_str())
347 .collect()
348 }
349
350 pub fn full_messages(&self) -> Vec<String> {
353 self.errors
354 .iter()
355 .map(|(n, m)| format!("{} {m}", humanize(n)))
356 .collect()
357 }
358
359 pub fn messages(&self) -> Vec<String> {
362 self.errors
363 .iter()
364 .map(|(n, m)| format!("{} {m}", n.replace('_', " ")))
365 .collect()
366 }
367
368 pub fn add_error<T>(
369 mut self,
370 column: impl FnOnce(&M::Columns) -> Col<M, T>,
371 message: impl Into<String>,
372 ) -> Self {
373 let name = column(&M::columns()).name();
374 self.errors.push((name, message.into()));
375 self
376 }
377
378 pub fn validate_required<T>(self, column: impl FnOnce(&M::Columns) -> Col<M, T>) -> Self {
380 self.validate_required_message(column, "can't be blank")
381 }
382
383 pub fn validate_required_message<T>(
386 self,
387 column: impl FnOnce(&M::Columns) -> Col<M, T>,
388 message: &str,
389 ) -> Self {
390 self.validate_with(column, |value| {
391 let blank = match value {
392 None | Some(Value::Null) => true,
393 Some(Value::Text(text)) => text.trim().is_empty(),
394 Some(_) => false,
395 };
396 blank.then(|| message.to_owned())
397 })
398 }
399
400 pub fn validate_length<T>(
403 self,
404 column: impl FnOnce(&M::Columns) -> Col<M, T>,
405 range: impl RangeBounds<usize>,
406 ) -> Self {
407 let min = match range.start_bound() {
408 Bound::Included(&n) => Some(n),
409 Bound::Excluded(&n) => Some(n + 1),
410 Bound::Unbounded => None,
411 };
412 let max = match range.end_bound() {
413 Bound::Included(&n) => Some(n),
414 Bound::Excluded(&n) => Some(n.saturating_sub(1)),
415 Bound::Unbounded => None,
416 };
417 self.validate_with(column, move |value| {
418 let Some(Value::Text(text)) = value else {
419 return None;
420 };
421 let len = text.chars().count();
422 match (min, max) {
423 (Some(min), _) if len < min => {
424 Some(format!("is too short (minimum is {min} characters)"))
425 }
426 (_, Some(max)) if len > max => {
427 Some(format!("is too long (maximum is {max} characters)"))
428 }
429 _ => None,
430 }
431 })
432 }
433
434 pub fn validate_format<T>(
441 self,
442 column: impl FnOnce(&M::Columns) -> Col<M, T>,
443 pattern: &str,
444 ) -> Self {
445 let regex = cached_regex(pattern);
446 self.validate_with(column, |value| match value {
447 Some(Value::Text(text)) if !regex.is_match(text) => Some("is invalid".to_owned()),
448 _ => None,
449 })
450 }
451
452 pub fn validate_inclusion<T>(
456 self,
457 column: impl FnOnce(&M::Columns) -> Col<M, T>,
458 allowed: &[&str],
459 ) -> Self {
460 self.validate_with(column, |value| match value {
461 None | Some(Value::Null) => None,
462 Some(value) => (!allowed.contains(&value.to_text().as_str()))
463 .then(|| "is not included in the list".to_owned()),
464 })
465 }
466
467 pub fn validate_numericality<T>(
471 self,
472 column: impl FnOnce(&M::Columns) -> Col<M, T>,
473 rules: Numericality,
474 ) -> Self {
475 self.validate_with(column, move |value| {
476 let number = match value {
477 None | Some(Value::Null) => return None,
478 Some(Value::Int(n)) => *n as f64,
479 Some(Value::Float(n)) => *n,
480 Some(Value::Decimal(n)) => n.to_string().parse().ok()?,
481 Some(Value::Text(text)) => match text.trim().parse::<f64>() {
482 Ok(n) => n,
483 Err(_) => return Some("is not a number".to_owned()),
484 },
485 Some(_) => return Some("is not a number".to_owned()),
486 };
487 rules.check(number)
488 })
489 }
490
491 pub fn validate_with<T>(
498 mut self,
499 column: impl FnOnce(&M::Columns) -> Col<M, T>,
500 check: impl FnOnce(Option<&Value>) -> Option<String>,
501 ) -> Self {
502 let name = column(&M::columns()).name();
503 if self.errors.iter().any(|(n, _)| *n == name) {
504 return self;
505 }
506 let value = self.value(name);
507 if let Some(message) = check(value.as_ref()) {
508 self.errors.push((name, message));
509 }
510 self
511 }
512
513 pub fn unique<T>(self, column: impl FnOnce(&M::Columns) -> Col<M, T>) -> Self {
518 self.unique_scoped(column, &[])
519 }
520
521 pub fn unique_scoped<T>(
524 mut self,
525 column: impl FnOnce(&M::Columns) -> Col<M, T>,
526 scope: &[&'static str],
527 ) -> Self {
528 let column = column(&M::columns()).name();
529 self.unique.push(column);
530 let mut scope = scope.to_vec();
532 for (owner, _) in M::OWNER {
533 if *owner != column && !scope.contains(owner) {
534 scope.push(owner);
535 }
536 }
537 self.unique_scopes.push((column, scope));
538 self
539 }
540
541 fn value_of(&self, column: &str) -> Value {
543 if let Some((_, value)) = self.changes.iter().find(|(c, _)| *c == column) {
544 return value.clone();
545 }
546 self.data
547 .as_ref()
548 .and_then(|data| data.values().into_iter().find(|(c, _)| *c == column))
549 .map_or(Value::Null, |(_, value)| value)
550 }
551
552 async fn check_parents(&mut self, conn: &Connection) -> Result<()> {
556 if M::OWNER.is_empty() {
557 return Ok(());
558 }
559 for parent in M::PARENTS {
560 let changed = self.changes.iter().any(|(name, _)| *name == parent.column);
561 if self.data.is_some() && !changed {
562 continue;
563 }
564 let id = self.value_of(parent.column);
565 if id == Value::Null {
566 continue;
567 }
568 let mut shared = Vec::new();
570 for (parent_column, key) in parent.owner {
571 if let Some((column, _)) = M::OWNER.iter().find(|(_, k)| k == key) {
572 shared.push((*parent_column, self.value_of(column)));
573 }
574 }
575 if shared.is_empty() {
576 continue;
577 }
578 let mut sql = Sql::new();
579 sql.push("SELECT 1 FROM ")
580 .push_ident(parent.table)
581 .push(" WHERE ")
582 .push_ident(parent.key)
583 .push(" = ")
584 .push_value(id);
585 for (column, value) in shared {
586 sql.push(" AND ")
587 .push_ident(column)
588 .push(" = ")
589 .push_value(value);
590 }
591 sql.push(" LIMIT 1");
592 if conn.fetch_all(&sql).await?.is_empty() {
593 self.errors
594 .push((parent.column, "isn't one of yours".to_owned()));
595 }
596 }
597 Ok(())
598 }
599
600 pub(crate) async fn check_unique(&mut self, conn: &Connection) -> Result<()> {
603 self.check_parents(conn).await?;
604 let checks = self.unique_scopes.clone();
605 for (column, scope) in checks {
606 let changed = |c: &str| self.changes.iter().any(|(name, _)| *name == c);
607 if self.data.is_some() && !changed(column) && !scope.iter().any(|c| changed(c)) {
608 continue;
609 }
610 let value = self.value_of(column);
611 if value == Value::Null || self.errors.iter().any(|(c, _)| *c == column) {
612 continue;
613 }
614 let mut sql = Sql::new();
615 sql.push("SELECT 1 FROM ")
616 .push_ident(M::TABLE)
617 .push(" WHERE ");
618 if M::DETERMINISTIC.contains(&column) {
619 sql.push_ident(column).push(" IN (");
621 let variants = crate::encryption::deterministic_variants(&value.to_text())?;
622 for (i, text) in variants.into_iter().enumerate() {
623 if i > 0 {
624 sql.push(", ");
625 }
626 sql.push_value(Value::Text(text));
627 }
628 sql.push(")");
629 } else {
630 sql.push_ident(column).push(" = ").push_value(value);
631 }
632 for scoped in &scope {
633 sql.push(" AND ").push_ident(scoped);
634 match self.value_of(scoped) {
635 Value::Null => sql.push(" IS NULL"),
636 value => sql.push(" = ").push_value(value),
637 };
638 }
639 if let Some(data) = &self.data {
640 sql.push(" AND ").push_ident(M::PRIMARY_KEY).push(" <> ");
641 sql.push_value(data.id_value());
642 }
643 sql.push(" LIMIT 1");
644 if !conn.fetch_all(&sql).await?.is_empty() {
645 let place = |c: &str| M::ATTRIBUTES.iter().position(|a| *a == c);
648 let at = self
649 .errors
650 .iter()
651 .position(|(c, _)| match (place(c), place(column)) {
652 (Some(theirs), Some(ours)) => theirs > ours,
653 (None, _) => true,
654 _ => false,
655 })
656 .unwrap_or(self.errors.len());
657 self.errors
658 .insert(at, (column, "has already been taken".to_owned()));
659 }
660 }
661 Ok(())
662 }
663
664 pub fn on(mut self, conn: impl Into<Connection>) -> Self {
666 self.conn = Some(conn.into());
667 self
668 }
669
670 pub(crate) fn connection(&self) -> Result<Connection> {
671 match &self.conn {
672 Some(conn) => Ok(conn.clone()),
673 None => current_in(M::DATABASE),
674 }
675 }
676
677 fn touch(&mut self, column: &'static str, now: Timestamp) {
678 if !self.changes.iter().any(|(n, _)| *n == column) {
679 self.changes.push((column, Value::Timestamp(now)));
680 }
681 }
682
683 pub async fn insert(self) -> Result<Save<M>> {
685 let mut changeset = M::validate(self);
686 if !changeset.is_valid() {
687 let conn = changeset.connection()?;
689 changeset.check_unique(&conn).await?;
690 return Ok(Save::Invalid(changeset));
691 }
692 changeset.insert_valid().await
693 }
694
695 pub(crate) async fn insert_valid(mut self) -> Result<Save<M>> {
696 let conn = self.connection()?;
697 self.check_unique(&conn).await?;
698 if !self.is_valid() {
699 return Ok(Save::Invalid(self));
700 }
701 let now = crate::time::now();
702 if let Some(column) = M::CREATED_AT {
703 self.touch(column, now);
704 }
705 if let Some(column) = M::UPDATED_AT {
706 self.touch(column, now);
707 }
708
709 let mut sql = Sql::new();
710 sql.push("INSERT INTO ").push_ident(M::TABLE);
711 if self.changes.is_empty() {
712 sql.push(" DEFAULT VALUES");
713 } else {
714 sql.push(" (");
715 for (i, (column, _)) in self.changes.iter().enumerate() {
716 if i > 0 {
717 sql.push(", ");
718 }
719 sql.push_ident(column);
720 }
721 sql.push(") VALUES (");
722 for (i, (column, value)) in self.changes.iter().enumerate() {
723 if i > 0 {
724 sql.push(", ");
725 }
726 sql.push_value(crate::encryption::stored::<M>(column, value.clone())?);
727 }
728 sql.push(")");
729 }
730 sql.push(" RETURNING *");
731 self.save(&conn, &sql).await
732 }
733
734 pub async fn update(self) -> Result<Save<M>> {
738 let mut changeset = M::validate(self);
739 if !changeset.is_valid() {
740 let conn = changeset.connection()?;
741 changeset.check_unique(&conn).await?;
742 return Ok(Save::Invalid(changeset));
743 }
744 changeset.update_valid().await
745 }
746
747 pub(crate) async fn update_valid(mut self) -> Result<Save<M>> {
748 let Some(data) = &self.data else {
749 return Err(Error::internal(
750 "update needs a record; use record.change()",
751 ));
752 };
753 if self.changes.is_empty() {
754 return Ok(Save::Saved(self.data.take().expect("checked above")));
755 }
756 data.check_not_shared()?;
757 let id = data.id_value();
758 let conn = self.connection()?;
759 self.check_unique(&conn).await?;
760 if !self.is_valid() {
761 return Ok(Save::Invalid(self));
762 }
763 if let Some(column) = M::UPDATED_AT {
764 self.touch(column, crate::time::now());
765 }
766
767 let mut sql = Sql::new();
768 sql.push("UPDATE ").push_ident(M::TABLE).push(" SET ");
769 for (i, (column, value)) in self.changes.iter().enumerate() {
770 if i > 0 {
771 sql.push(", ");
772 }
773 sql.push_ident(column).push(" = ");
774 sql.push_value(crate::encryption::stored::<M>(column, value.clone())?);
775 }
776 sql.push(" WHERE ").push_ident(M::PRIMARY_KEY).push(" = ");
777 sql.push_value(id);
778 sql.push(" RETURNING *");
779 self.save(&conn, &sql).await
780 }
781
782 async fn save(self, conn: &Connection, sql: &Sql) -> Result<Save<M>> {
783 let savepoint = (conn.in_transaction()
787 && conn.dialect() == Dialect::Postgres
788 && !self.unique.is_empty())
789 .then(|| format!("glacier_{}", SAVEPOINTS.fetch_add(1, Ordering::Relaxed)));
790 if let Some(name) = &savepoint {
791 conn.execute(Sql::new().push(&format!("SAVEPOINT {name}")))
792 .await?;
793 }
794 let result = conn.fetch_all(sql).await;
795 if let Some(name) = &savepoint {
796 let finish = if result.is_ok() {
797 format!("RELEASE SAVEPOINT {name}")
798 } else {
799 format!("ROLLBACK TO SAVEPOINT {name}")
800 };
801 conn.execute(Sql::new().push(&finish)).await?;
802 }
803 match result {
804 Ok(rows) => match rows.first() {
805 Some(row) => {
806 let saved = M::from_row(row)?;
807 saved.touch_parents().await?;
809 Ok(Save::Saved(saved))
810 }
811 None => Err(Error::not_found()),
812 },
813 Err(sqlx::Error::Database(err)) if err.is_unique_violation() => {
814 match self.unique_column(err.message(), err.constraint()) {
815 Some(column) => {
816 let mut changeset = self;
817 changeset
818 .errors
819 .push((column, "has already been taken".to_owned()));
820 Ok(Save::Invalid(changeset))
821 }
822 None => Err(sqlx::Error::Database(err).into()),
823 }
824 }
825 Err(err) => Err(err.into()),
826 }
827 }
828
829 fn unique_column(&self, message: &str, constraint: Option<&str>) -> Option<&'static str> {
832 let haystack = format!("{message} {}", constraint.unwrap_or_default());
833 self.unique
834 .iter()
835 .copied()
836 .find(|column| haystack.contains(column))
837 .or_else(|| (self.unique.len() == 1).then(|| self.unique[0]))
838 }
839}
840
841#[derive(Debug, Clone, Copy, Default, PartialEq)]
844pub struct Numericality {
845 pub only_integer: bool,
846 pub greater_than: Option<f64>,
847 pub greater_than_or_equal_to: Option<f64>,
848 pub less_than: Option<f64>,
849 pub less_than_or_equal_to: Option<f64>,
850}
851
852impl Numericality {
853 fn check(&self, n: f64) -> Option<String> {
854 let shown = |bound: f64| {
856 if bound.fract() == 0.0 && bound.abs() < 1e15 {
857 format!("{}", bound as i64)
858 } else {
859 bound.to_string()
860 }
861 };
862 if self.only_integer && n.fract() != 0.0 {
863 return Some("must be an integer".to_owned());
864 }
865 if let Some(b) = self.greater_than.filter(|b| n <= *b) {
866 return Some(format!("must be greater than {}", shown(b)));
867 }
868 if let Some(b) = self.greater_than_or_equal_to.filter(|b| n < *b) {
869 return Some(format!("must be greater than or equal to {}", shown(b)));
870 }
871 if let Some(b) = self.less_than.filter(|b| n >= *b) {
872 return Some(format!("must be less than {}", shown(b)));
873 }
874 if let Some(b) = self.less_than_or_equal_to.filter(|b| n > *b) {
875 return Some(format!("must be less than or equal to {}", shown(b)));
876 }
877 None
878 }
879}
880
881fn cached_regex(pattern: &str) -> regex::Regex {
883 use std::collections::HashMap;
884 use std::sync::{Mutex, OnceLock};
885 static CACHE: OnceLock<Mutex<HashMap<String, regex::Regex>>> = OnceLock::new();
886 let mut cache = CACHE
887 .get_or_init(Default::default)
888 .lock()
889 .unwrap_or_else(|e| e.into_inner());
890 cache
891 .entry(pattern.to_owned())
892 .or_insert_with(|| {
893 regex::Regex::new(pattern)
894 .unwrap_or_else(|e| panic!("invalid format pattern {pattern:?}: {e}"))
895 })
896 .clone()
897}
898
899pub(crate) fn humanize(column: &str) -> String {
902 let words = column
903 .strip_suffix("_id")
904 .unwrap_or(column)
905 .replace('_', " ");
906 let mut chars = words.chars();
907 match chars.next() {
908 Some(first) => first.to_uppercase().chain(chars).collect(),
909 None => String::new(),
910 }
911}