uqa-sql 0.6.1

PostgreSQL-compatible SQL compiler built on libpg_query
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! `PostgreSQL` COPY text and CSV stream codecs.

use super::{CopyFormat, CopyHeader, CopyInputField, CopyOptions};
use crate::{SQLError, SQLResult};

/// Decode a complete text or CSV COPY stream into rows.
pub fn decode_copy_input(
    bytes: &[u8],
    options: &CopyOptions,
    expected_columns: &[String],
) -> Result<Vec<Vec<CopyInputField>>, SQLError> {
    if options.format == CopyFormat::Binary {
        return Err(SQLError::Unsupported(
            "binary COPY format is not implemented".into(),
        ));
    }
    let input = copy_utf8(bytes)?;
    let mut rows = match options.format {
        CopyFormat::Text => decode_text_rows(input, options)?,
        CopyFormat::Csv => decode_csv_rows(input, options)?,
        CopyFormat::Binary => unreachable!(),
    };
    if options.header != CopyHeader::False {
        if rows.is_empty() {
            return Ok(Vec::new());
        }
        let header = rows.remove(0);
        if options.header == CopyHeader::Match {
            let actual = header
                .into_iter()
                .map(|field| field.unwrap_or_default())
                .collect::<Vec<_>>();
            if actual != expected_columns {
                return Err(copy_data_error(
                    "22P04",
                    format!(
                        "wrong number of fields in header line: expected {expected_columns:?}, got {actual:?}"
                    ),
                    1,
                ));
            }
        }
    }
    let first_data_line = usize::from(options.header != CopyHeader::False) + 1;
    for (index, row) in rows.iter().enumerate() {
        if row.len() > expected_columns.len() {
            return Err(copy_data_error(
                "22P04",
                "extra data after last expected column",
                index + first_data_line,
            ));
        }
        if row.len() < expected_columns.len() {
            return Err(copy_data_error(
                "22P04",
                format!(
                    "missing data for column \"{}\"",
                    expected_columns[row.len()]
                ),
                index + first_data_line,
            ));
        }
    }
    Ok(rows)
}

fn decode_text_rows(
    input: &str,
    options: &CopyOptions,
) -> Result<Vec<Vec<CopyInputField>>, SQLError> {
    let mut rows = Vec::new();
    for (line_index, raw) in logical_text_lines(input).into_iter().enumerate() {
        if raw == "\\." {
            break;
        }
        rows.push(decode_text_row(raw, options, line_index + 1)?);
    }
    Ok(rows)
}

fn decode_text_row(
    raw: &str,
    options: &CopyOptions,
    line: usize,
) -> Result<Vec<CopyInputField>, SQLError> {
    let bytes = raw.as_bytes();
    let mut fields = Vec::new();
    let mut field_start = 0usize;
    let mut index = 0usize;
    while index < bytes.len() {
        if bytes[index] == options.delimiter {
            fields.push(decode_text_input_field(
                &raw[field_start..index],
                options,
                line,
            )?);
            index += 1;
            field_start = index;
            continue;
        }
        if bytes[index] != b'\\' {
            index += 1;
            continue;
        }
        index += 1;
        if index == bytes.len() {
            return Err(copy_data_error(
                "22P04",
                "unterminated COPY data escape",
                line,
            ));
        }
        match bytes[index] {
            b'x' => {
                index += 1;
                for _ in 0..2 {
                    if index >= bytes.len() || hex_value(bytes[index]).is_none() {
                        break;
                    }
                    index += 1;
                }
            }
            b'0'..=b'7' => {
                index += 1;
                for _ in 0..2 {
                    if index >= bytes.len() || !(b'0'..=b'7').contains(&bytes[index]) {
                        break;
                    }
                    index += 1;
                }
            }
            _ => index += 1,
        }
    }
    fields.push(decode_text_input_field(&raw[field_start..], options, line)?);
    Ok(fields)
}

fn decode_text_input_field(
    raw: &str,
    options: &CopyOptions,
    line: usize,
) -> Result<CopyInputField, SQLError> {
    if raw == options.null {
        Ok(None)
    } else {
        decode_text_field(raw, line).map(Some)
    }
}

fn logical_text_lines(input: &str) -> Vec<&str> {
    if input.is_empty() {
        return Vec::new();
    }
    let mut lines = input.split('\n').collect::<Vec<_>>();
    if input.ends_with('\n') {
        lines.pop();
    }
    for line in &mut lines {
        if let Some(without_cr) = line.strip_suffix('\r') {
            *line = without_cr;
        }
    }
    lines
}

fn decode_text_field(raw: &str, line: usize) -> Result<String, SQLError> {
    let bytes = raw.as_bytes();
    let mut output = Vec::with_capacity(bytes.len());
    let mut index = 0;
    while index < bytes.len() {
        if bytes[index] != b'\\' {
            output.push(bytes[index]);
            index += 1;
            continue;
        }
        index += 1;
        if index == bytes.len() {
            return Err(copy_data_error(
                "22P04",
                "unterminated COPY data escape",
                line,
            ));
        }
        match bytes[index] {
            b'b' => output.push(0x08),
            b'f' => output.push(0x0c),
            b'n' => output.push(b'\n'),
            b'r' => output.push(b'\r'),
            b't' => output.push(b'\t'),
            b'v' => output.push(0x0b),
            b'x' => {
                let mut value = 0u8;
                let mut digits = 0usize;
                while digits < 2 && index + 1 < bytes.len() {
                    let Some(nibble) = hex_value(bytes[index + 1]) else {
                        break;
                    };
                    value = value * 16 + nibble;
                    index += 1;
                    digits += 1;
                }
                if digits == 0 {
                    output.push(b'x');
                } else {
                    output.push(value);
                }
            }
            digit @ b'0'..=b'7' => {
                let mut value = digit - b'0';
                let mut digits = 1usize;
                while digits < 3 && index + 1 < bytes.len() {
                    let next = bytes[index + 1];
                    if !(b'0'..=b'7').contains(&next) {
                        break;
                    }
                    value = value.wrapping_mul(8).wrapping_add(next - b'0');
                    index += 1;
                    digits += 1;
                }
                output.push(value);
            }
            escaped => output.push(escaped),
        }
        index += 1;
    }
    if output.contains(&0) {
        return Err(copy_encoding_error(Some(line)));
    }
    String::from_utf8(output).map_err(|_| copy_encoding_error(Some(line)))
}

fn hex_value(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        _ => None,
    }
}

fn decode_csv_rows(
    input: &str,
    options: &CopyOptions,
) -> Result<Vec<Vec<CopyInputField>>, SQLError> {
    let bytes = input.as_bytes();
    let mut rows = Vec::new();
    let mut row = Vec::new();
    let mut field = Vec::new();
    let mut quoted = false;
    let mut in_quotes = false;
    let mut after_quote = false;
    let mut index = 0usize;
    let mut line = 1usize;
    while index < bytes.len() {
        let byte = bytes[index];
        if in_quotes {
            if byte == options.escape {
                if index + 1 < bytes.len()
                    && matches!(bytes[index + 1], next if next == options.quote || next == options.escape)
                {
                    field.push(bytes[index + 1]);
                    index += 2;
                    continue;
                }
                if options.escape != options.quote {
                    field.push(byte);
                    index += 1;
                    continue;
                }
            }
            if byte == options.quote {
                in_quotes = false;
                after_quote = true;
                index += 1;
                continue;
            }
            if byte == b'\n' {
                line += 1;
            }
            field.push(byte);
            index += 1;
            continue;
        }
        if after_quote && !matches!(byte, b'\n' | b'\r') && byte != options.delimiter {
            field.push(byte);
            index += 1;
            continue;
        }
        if byte == options.delimiter {
            row.push(csv_field(&field, quoted, options)?);
            field.clear();
            quoted = false;
            after_quote = false;
            index += 1;
            continue;
        }
        if byte == b'\n' || byte == b'\r' {
            if byte == b'\r' && index + 1 < bytes.len() && bytes[index + 1] == b'\n' {
                index += 1;
            }
            row.push(csv_field(&field, quoted, options)?);
            if row.len() == 1 && row[0].as_deref() == Some("\\.") && !quoted {
                return Ok(rows);
            }
            rows.push(std::mem::take(&mut row));
            field.clear();
            quoted = false;
            after_quote = false;
            index += 1;
            line += 1;
            continue;
        }
        if byte == options.quote && field.is_empty() && !after_quote {
            quoted = true;
            in_quotes = true;
            index += 1;
            continue;
        }
        field.push(byte);
        index += 1;
    }
    if in_quotes {
        return Err(copy_data_error(
            "22P04",
            "unterminated CSV quoted field",
            line,
        ));
    }
    if !field.is_empty() || !row.is_empty() || quoted || after_quote {
        row.push(csv_field(&field, quoted, options)?);
        if !(row.len() == 1 && row[0].as_deref() == Some("\\.") && !quoted) {
            rows.push(row);
        }
    }
    Ok(rows)
}

fn csv_field(
    field: &[u8],
    quoted: bool,
    options: &CopyOptions,
) -> Result<CopyInputField, SQLError> {
    let text = copy_utf8(field)?;
    if !quoted && text == options.null {
        Ok(None)
    } else {
        Ok(Some(text.to_string()))
    }
}

fn copy_data_error(sqlstate: &str, message: impl Into<String>, line: usize) -> SQLError {
    SQLError::Routine {
        sqlstate: sqlstate.into(),
        message: format!("{}\nCONTEXT: COPY data, line {line}", message.into()),
    }
}

fn copy_utf8(bytes: &[u8]) -> Result<&str, SQLError> {
    if bytes.contains(&0) {
        return Err(copy_encoding_error(None));
    }
    std::str::from_utf8(bytes).map_err(|_| copy_encoding_error(None))
}

fn copy_encoding_error(line: Option<usize>) -> SQLError {
    let context = line.map_or_else(String::new, |line| format!(" at line {line}"));
    SQLError::Routine {
        sqlstate: "22021".into(),
        message: format!("invalid byte sequence for encoding \"UTF8\" in COPY data{context}"),
    }
}

/// Encode one SQL result using `PostgreSQL` COPY text or CSV representation.
pub fn encode_copy_result(result: &SQLResult, options: &CopyOptions) -> Result<Vec<u8>, SQLError> {
    let mut output = Vec::new();
    super::output::write_copy_result(
        result,
        options,
        &mut output,
        None,
        &uqa_core::memory::ProductionControl::uncontrolled(),
    )?;
    Ok(output)
}

/// Encode one SQL result while resolving catalog-backed `reg*` text output through the engine hook.
pub fn encode_copy_result_with_engine(
    result: &SQLResult,
    options: &CopyOptions,
    engine: &dyn crate::expr::EngineHook,
) -> Result<Vec<u8>, SQLError> {
    let mut output = Vec::new();
    super::output::write_copy_result(
        result,
        options,
        &mut output,
        Some(engine),
        &uqa_core::memory::ProductionControl::uncontrolled(),
    )?;
    Ok(output)
}