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