1use crate::{
2 DataSet, 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}
19
20impl TableRef {
21 pub fn new(name: impl Into<Cow<'static, str>>) -> Self {
23 Self {
24 name: name.into(),
25 schema: "".into(),
26 alias: "".into(),
27 }
28 }
29 pub fn full_name(&self) -> String {
31 let mut result = String::new();
32 if !self.alias.is_empty() {
33 result.push_str(&self.alias);
34 } else {
35 if !self.schema.is_empty() {
36 result.push_str(&self.schema);
37 result.push('.');
38 }
39 result.push_str(&self.name);
40 }
41 result
42 }
43 pub fn with_alias(&self, alias: Cow<'static, str>) -> Self {
45 let mut result = self.clone();
46 result.alias = alias.into();
47 result
48 }
49 pub fn name<'s>(&'s self) -> &'s str {
51 &self.name
53 }
54 pub fn schema<'s>(&'s self) -> &'s str {
56 &self.schema
58 }
59 pub fn alias<'s>(&'s self) -> &'s str {
61 &self.alias
63 }
64}
65
66impl DataSet for TableRef {
67 fn qualified_columns() -> bool
68 where
69 Self: Sized,
70 {
71 false
72 }
73 fn write_query(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut String) {
74 writer.write_table_ref(context, out, self)
75 }
76}
77
78impl DataSet for &TableRef {
79 fn qualified_columns() -> bool
80 where
81 Self: Sized,
82 {
83 false
84 }
85 fn write_query(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut String) {
86 (*writer).write_table_ref(context, out, self)
87 }
88}
89
90impl ToTokens for TableRef {
91 fn to_tokens(&self, tokens: &mut TokenStream) {
92 let name = &self.name;
93 let schema = &self.schema;
94 let alias = quote_cow(&self.alias);
95 tokens.append_all(quote! {
96 ::tank::TableRef {
97 name: #name,
98 schema: #schema,
99 alias: #alias,
100 }
101 });
102 }
103}
104
105#[derive(Default, Clone, PartialEq, Eq, Debug)]
107pub struct DeclareTableRef(pub TableRef);
108
109impl DataSet for DeclareTableRef {
110 fn qualified_columns() -> bool
111 where
112 Self: Sized,
113 {
114 false
115 }
116 fn write_query(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut String) {
117 writer.write_table_ref(context, out, &self.0)
118 }
119}
120
121impl ToTokens for DeclareTableRef {
122 fn to_tokens(&self, tokens: &mut TokenStream) {
123 let table_ref = &self.0;
124 tokens.append_all(quote!(::tank::DeclareTableRef(#table_ref)));
125 }
126}