1use crate::{
2 ColumnDef, Dataset, DynQuery, quote_cow,
3 writer::{Context, SqlWriter},
4};
5use proc_macro2::TokenStream;
6use quote::{ToTokens, TokenStreamExt, quote};
7use std::borrow::Cow;
8
9#[derive(Default, Clone, PartialEq, Eq, Hash, Debug)]
11pub struct TableRef {
12 pub name: Cow<'static, str>,
14 pub schema: Cow<'static, str>,
16 pub alias: Cow<'static, str>,
18 pub columns: &'static [ColumnDef],
20 pub primary_key: &'static [&'static ColumnDef],
22}
23
24impl TableRef {
25 pub const fn new(name: Cow<'static, str>) -> Self {
27 Self {
28 name,
29 schema: Cow::Borrowed(""),
30 alias: Cow::Borrowed(""),
31 columns: &[],
32 primary_key: &[],
33 }
34 }
35 pub fn full_name(&self, separator: &str) -> Cow<'static, str> {
37 if !self.alias.is_empty() {
38 return self.alias.clone();
39 }
40 if !self.schema.is_empty() {
41 return format!("{}{}{}", self.schema, separator, self.name).into();
42 }
43 self.name.clone()
44 }
45 pub fn with_alias(&self, alias: Cow<'static, str>) -> Self {
47 let mut result = self.clone();
48 result.alias = alias.into();
49 result
50 }
51 pub fn is_empty(&self) -> bool {
53 self.name.is_empty() && self.schema.is_empty() && self.alias.is_empty()
54 }
55}
56
57impl Dataset for TableRef {
58 fn qualified_columns() -> bool
59 where
60 Self: Sized,
61 {
62 false
63 }
64 fn write_table_name(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut DynQuery) {
65 writer.write_table_ref(context, out, self)
66 }
67 fn table_ref(&self) -> TableRef {
68 self.clone()
69 }
70}
71
72impl Dataset for &TableRef {
73 fn qualified_columns() -> bool
74 where
75 Self: Sized,
76 {
77 false
78 }
79 fn write_table_name(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut DynQuery) {
80 (*writer).write_table_ref(context, out, self)
81 }
82 fn table_ref(&self) -> TableRef {
83 (*self).clone()
84 }
85}
86
87impl From<&'static str> for TableRef {
88 fn from(value: &'static str) -> Self {
89 TableRef::new(value.into())
90 }
91}
92
93impl ToTokens for TableRef {
94 fn to_tokens(&self, tokens: &mut TokenStream) {
95 let name = &self.name;
96 let schema = &self.schema;
97 let alias = quote_cow(&self.alias);
98 tokens.append_all(quote! {
99 ::tank::TableRef {
100 name: #name,
101 schema: #schema,
102 alias: #alias,
103 }
104 });
105 }
106}
107
108#[derive(Default, Clone, PartialEq, Eq, Debug)]
110pub struct DeclareTableRef(pub TableRef);
111
112impl Dataset for DeclareTableRef {
113 fn qualified_columns() -> bool
114 where
115 Self: Sized,
116 {
117 false
118 }
119 fn write_table_name(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut DynQuery) {
120 writer.write_table_ref(context, out, &self.0)
121 }
122 fn table_ref(&self) -> TableRef {
123 self.0.clone()
124 }
125}
126
127impl ToTokens for DeclareTableRef {
128 fn to_tokens(&self, tokens: &mut TokenStream) {
129 let table_ref = &self.0;
130 tokens.append_all(quote!(::tank::DeclareTableRef(#table_ref)));
131 }
132}