1use crate::{Expression, OpPrecedence, TableRef, Value, writer::Context};
2use proc_macro2::TokenStream;
3use quote::{ToTokens, TokenStreamExt, quote};
4
5pub trait ColumnTrait {
6 fn column_def(&self) -> &ColumnDef;
7 fn column_ref(&self) -> &ColumnRef;
8}
9
10#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
11pub struct ColumnRef {
12 pub name: &'static str,
13 pub table: &'static str,
14 pub schema: &'static str,
15}
16
17impl ColumnRef {
18 pub fn table_ref(&self) -> TableRef {
19 TableRef {
20 name: self.table,
21 schema: self.schema,
22 ..Default::default()
23 }
24 }
25}
26
27#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
28pub enum PrimaryKeyType {
29 PrimaryKey,
30 PartOfPrimaryKey,
31 #[default]
32 None,
33}
34
35impl ToTokens for PrimaryKeyType {
36 fn to_tokens(&self, tokens: &mut TokenStream) {
37 use PrimaryKeyType::*;
38 tokens.append_all(match self {
39 PrimaryKey => quote!(::tank::PrimaryKeyType::PrimaryKey),
40 PartOfPrimaryKey => quote!(::tank::PrimaryKeyType::PartOfPrimaryKey),
41 None => quote!(::tank::PrimaryKeyType::None),
42 });
43 }
44}
45
46#[derive(Default, Debug)]
47pub struct ColumnDef {
48 pub column_ref: ColumnRef,
49 pub column_type: &'static str,
50 pub value: Value,
51 pub nullable: bool,
52 pub default: Option<Box<dyn Expression>>,
53 pub primary_key: PrimaryKeyType,
54 pub unique: bool,
55 pub references: Option<ColumnRef>,
56 pub passive: bool,
57 pub comment: &'static str,
58}
59
60impl ColumnDef {
61 pub fn name(&self) -> &'static str {
62 &self.column_ref.name
63 }
64 pub fn table(&self) -> &'static str {
65 &self.column_ref.table
66 }
67 pub fn schema(&self) -> &'static str {
68 &self.column_ref.schema
69 }
70}
71
72impl<'a> From<&'a ColumnDef> for &'a ColumnRef {
73 fn from(value: &'a ColumnDef) -> Self {
74 &value.column_ref
75 }
76}
77
78impl OpPrecedence for ColumnRef {
79 fn precedence(&self, _writer: &dyn crate::SqlWriter) -> i32 {
80 1_000_000
81 }
82}
83
84impl Expression for ColumnRef {
85 fn write_query(&self, writer: &dyn crate::SqlWriter, context: Context, buff: &mut String) {
86 writer.write_column_ref(context, buff, self);
87 }
88}
89
90impl OpPrecedence for ColumnDef {
91 fn precedence(&self, _writer: &dyn crate::SqlWriter) -> i32 {
92 1_000_000
93 }
94}
95
96impl Expression for ColumnDef {
97 fn write_query(&self, writer: &dyn crate::SqlWriter, context: Context, buff: &mut String) {
98 writer.write_column_ref(context, buff, &self.column_ref);
99 }
100}