1use std::{collections::BTreeMap, fmt::Write};
2use tank_core::{
3 ColumnDef, Context, Dataset, DynQuery, Expression, Fragment, SqlWriter, TableRef, Value,
4 separated_by,
5};
6use time::{Date, OffsetDateTime, PrimitiveDateTime, Time};
7
8pub struct PostgresSqlWriter {}
10
11impl PostgresSqlWriter {
12 pub fn write_copy(&self, out: &mut DynQuery, table: &TableRef) {
14 out.buffer().reserve(128);
15 out.push_str("COPY ");
16 let mut context = Context::new(Default::default(), table.qualified_columns());
17 self.write_table_ref(&mut context, out, table);
18 out.push_str(" (");
19 separated_by(
20 out,
21 table.columns.iter(),
22 |out, col| {
23 self.write_identifier(&mut context, out, col.name(), true);
24 },
25 ", ",
26 );
27 out.push_str(") FROM STDIN BINARY;");
28 }
29}
30
31impl SqlWriter for PostgresSqlWriter {
32 fn as_dyn(&self) -> &dyn SqlWriter {
33 self
34 }
35
36 fn write_column_overridden_type(
37 &self,
38 _context: &mut Context,
39 out: &mut DynQuery,
40 _column: &ColumnDef,
41 types: &BTreeMap<&'static str, &'static str>,
42 ) {
43 if let Some(t) = types.iter().find_map(|(k, v)| {
44 if *k == "postgres" || *k == "postgresql" {
45 Some(v)
46 } else {
47 None
48 }
49 }) {
50 out.push_str(t);
51 }
52 }
53
54 fn write_column_type(&self, context: &mut Context, out: &mut DynQuery, value: &Value<'_>) {
55 match value {
56 Value::Boolean(..) => out.push_str("BOOLEAN"),
57 Value::Int8(..) => out.push_str("SMALLINT"),
58 Value::Int16(..) => out.push_str("SMALLINT"),
59 Value::Int32(..) => out.push_str("INTEGER"),
60 Value::Int64(..) => out.push_str("BIGINT"),
61 Value::Int128(..) => out.push_str("NUMERIC(39)"),
62 Value::UInt8(..) => out.push_str("SMALLINT"),
63 Value::UInt16(..) => out.push_str("INTEGER"),
64 Value::UInt32(..) => out.push_str("BIGINT"),
65 Value::UInt64(..) => out.push_str("NUMERIC(19)"),
66 Value::UInt128(..) => out.push_str("NUMERIC(39)"),
67 Value::Float32(..) => out.push_str("FLOAT4"),
68 Value::Float64(..) => out.push_str("FLOAT8"),
69 Value::Decimal(_, precision, scale, ..) => {
70 out.push_str("NUMERIC");
71 if (precision, scale) != (&0, &0) {
72 let _ = write!(out, "({},{})", precision, scale);
73 }
74 }
75 Value::Char(..) => out.push_str("CHAR(1)"),
76 Value::Varchar(..) => out.push_str("TEXT"),
77 Value::Blob(..) => out.push_str("BYTEA"),
78 Value::Date(..) => out.push_str("DATE"),
79 Value::Time(..) => out.push_str("TIME"),
80 Value::Timestamp(..) => out.push_str("TIMESTAMP"),
81 Value::TimestampWithTimezone(..) => out.push_str("TIMESTAMP WITH TIME ZONE"),
82 Value::Interval(..) => out.push_str("INTERVAL"),
83 Value::Uuid(..) => out.push_str("UUID"),
84 Value::Array(_, t, ..) => {
85 self.write_column_type(context, out, &t.element);
86 let _ = write!(out, "[{}]", t.len);
87 }
88 Value::List(_, t, ..) => {
89 self.write_column_type(context, out, &t.element);
90 out.push_str("[]");
91 }
92 Value::Map(..) | Value::Json(..) | Value::Struct(..) => out.push_str("JSON"),
93 _ => log::error!("Unexpected tank::Value, Postgres does not support {value:?}"),
94 };
95 }
96
97 fn write_blob(&self, _context: &mut Context, out: &mut DynQuery, value: &[u8]) {
98 out.push_str("'\\x");
99 for b in value {
100 let _ = write!(out, "{:02X}", b);
101 }
102 out.push('\'');
103 }
104
105 fn write_date(&self, context: &mut Context, out: &mut DynQuery, value: &Date) {
106 let (l, r) = match context.fragment {
107 Fragment::None | Fragment::ParameterBinding | Fragment::Timestamp => ("", ""),
108 Fragment::Json | Fragment::JsonKey => ("\"", "\""),
109 _ => ("'", "'::DATE"),
110 };
111 let (year, suffix) = if value.year() <= 0 {
112 let suffix = if context.fragment == Fragment::Timestamp {
114 ""
115 } else {
116 " BC"
117 };
118 (value.year().abs() + 1, suffix)
119 } else {
120 (value.year(), "")
121 };
122 let month = value.month() as u8;
123 let day = value.day();
124 let _ = write!(out, "{l}{year:04}-{month:02}-{day:02}{suffix}{r}");
125 }
126
127 fn write_time(&self, context: &mut Context, out: &mut DynQuery, value: &Time) {
128 let (l, r) = match context.fragment {
129 Fragment::None | Fragment::ParameterBinding | Fragment::Timestamp => ("", ""),
130 Fragment::Json | Fragment::JsonKey => ("\"", "\""),
131 _ => ("'", "'::TIME"),
132 };
133 let (h, m, s, ns) = value.as_hms_nano();
134 let mut subsecond = ns;
135 let mut width = 9;
136 while width > 1 && subsecond % 10 == 0 {
137 subsecond /= 10;
138 width -= 1;
139 }
140 let _ = write!(out, "{l}{h:02}:{m:02}:{s:02}.{subsecond:0width$}{r}",);
141 }
142
143 fn write_timestamp(
144 &self,
145 context: &mut Context,
146 out: &mut DynQuery,
147 value: &PrimitiveDateTime,
148 ) {
149 let is_timestamp = context.fragment == Fragment::Timestamp;
150 let (l, r) = match context.fragment {
151 Fragment::None | Fragment::ParameterBinding | Fragment::Timestamp => ("", ""),
152 Fragment::Json | Fragment::JsonKey => ("\"", "\""),
153 _ => ("'", "'::TIMESTAMP"),
154 };
155 let mut context = context.switch_fragment(Fragment::Timestamp);
156 out.push_str(l);
157 self.write_date(&mut context.current, out, &value.date());
158 out.push('T');
159 self.write_time(&mut context.current, out, &value.time());
160 if !is_timestamp && value.date().year() <= 0 {
161 out.push_str(" BC");
162 }
163 out.push_str(r);
164 }
165
166 fn write_timestamptz(&self, context: &mut Context, out: &mut DynQuery, value: &OffsetDateTime) {
167 let (l, r) = match context.fragment {
168 Fragment::None | Fragment::ParameterBinding | Fragment::Timestamp => ("", ""),
169 Fragment::Json | Fragment::JsonKey => ("\"", "\""),
170 _ => ("'", "'::TIMESTAMPTZ"),
171 };
172 let mut context = context.switch_fragment(Fragment::Timestamp);
173 out.push_str(l);
174 self.write_timestamp(
175 &mut context.current,
176 out,
177 &PrimitiveDateTime::new(value.date(), value.time()),
178 );
179 let total_minutes = value.offset().whole_minutes();
180 let sign = if total_minutes >= 0 { '+' } else { '-' };
181 let _ = write!(
182 out,
183 "{}{:02}:{:02}",
184 sign,
185 (total_minutes.abs() / 60) as u8,
186 (total_minutes.abs() % 60) as u8
187 );
188 if value.date().year() <= 0 {
189 out.push_str(" BC");
190 }
191 out.push_str(r);
192 }
193
194 fn write_list(
195 &self,
196 context: &mut Context,
197 out: &mut DynQuery,
198 value: &mut dyn Iterator<Item = &dyn Expression>,
199 ty: Option<&Value<'_>>,
200 _is_array: bool,
201 ) {
202 out.push_str("ARRAY[");
203 separated_by(
204 out,
205 value,
206 |out, v| {
207 v.write_query(self, context, out);
208 },
209 ",",
210 );
211 out.push(']');
212 if let Some(ty) = ty {
213 out.push_str("::");
214 self.write_column_type(context, out, ty);
215 out.push_str("[]");
216 }
217 }
218
219 fn write_question_mark(&self, context: &mut Context, out: &mut DynQuery) {
220 context.counter += 1;
221 let _ = write!(out, "${}", context.counter);
222 }
223
224 fn write_current_timestamp_ms(&self, _context: &mut Context, out: &mut DynQuery) {
225 out.push_str("CAST(EXTRACT(EPOCH FROM NOW()) * 1000 AS BIGINT)");
226 }
227}