good_ormning/pg/graph/
table.rs1use std::collections::HashSet;
2use crate::{
3 pg::{
4 schema::{
5 table::Table,
6 field::Field,
7 },
8 types::to_sql_type,
9 },
10 graphmigrate::Comparison,
11 utils::Tokens,
12};
13use super::{
14 utils::{
15 NodeData,
16 PgMigrateCtx,
17 NodeDataDispatch,
18 },
19 Node,
20 GraphId,
21};
22
23#[derive(Clone)]
24pub struct NodeTable_ {
25 pub def: Table,
26 pub fields: Vec<Field>,
27}
28
29impl NodeTable_ {
30 pub fn compare(&self, old: &Self, _created: &HashSet<GraphId>) -> Comparison {
31 if old.def.id != self.def.id {
32 Comparison::Update
33 } else {
34 Comparison::DoNothing
35 }
36 }
37}
38
39impl NodeData for NodeTable_ {
40 fn update(&self, ctx: &mut PgMigrateCtx, old: &Self) {
41 if old.def.id != self.def.id {
42 let mut stmt = Tokens::new();
43 stmt.s("alter table").id(&old.def.id).s("rename to").id(&self.def.id);
44 ctx.statements.push(stmt.to_string());
45 }
46 }
47}
48
49impl NodeDataDispatch for NodeTable_ {
50 fn create_coalesce(&mut self, other: Node) -> Option<Node> {
51 match other {
52 Node::Field(f) if f.def.table == self.def => {
53 self.fields.push(f.def.clone());
54 None
55 },
56 other => Some(other),
57 }
58 }
59
60 fn delete_coalesce(&mut self, other: Node) -> Option<Node> {
61 match other {
62 Node::Field(f) if f.def.table == self.def => None,
63 Node::Constraint(e) if e.def.table == self.def => None,
64 Node::Index(e) if e.def.table == self.def => None,
65 other => Some(other),
66 }
67 }
68
69 fn create(&self, ctx: &mut PgMigrateCtx) {
70 let mut stmt = Tokens::new();
71 stmt.s("create table").id(&self.def.id).s("(");
72 for (i, f) in self.fields.iter().enumerate() {
73 if i > 0 {
74 stmt.s(",");
75 }
76 stmt.id(&f.id).s(to_sql_type(&f.0.type_.type_.type_.type_));
77 if !f.type_.type_.opt {
78 stmt.s("not null");
79 }
80 }
81 stmt.s(")");
82 ctx.statements.push(stmt.to_string());
83 }
84
85 fn delete(&self, ctx: &mut PgMigrateCtx) {
86 ctx.statements.push(Tokens::new().s("drop table").id(&self.def.id).to_string());
87 }
88}