Skip to main content

sql_splitter/
copy_data.rs

1//! Shared helpers for PostgreSQL COPY data blocks.
2//!
3//! The parser emits a COPY statement's data section (the lines between
4//! `COPY ... FROM stdin;` and the `\.` terminator) as a separate "Unknown"
5//! statement. Both `validate` and `diff` need to recognize such blocks and
6//! trim their leading whitespace; this module owns that logic so the two
7//! commands (and any future COPY consumer) cannot drift.
8
9/// Returns true if `stmt` looks like a PostgreSQL COPY data block, i.e. it
10/// ends with the `\.` terminator line.
11pub fn is_copy_data_block(stmt: &[u8]) -> bool {
12    stmt.ends_with(b"\\.\n") || stmt.ends_with(b"\\.\r\n")
13}
14
15/// Trim leading whitespace/newlines from a COPY data block without copying.
16///
17/// The block as emitted by the parser may start with the newline that
18/// followed the COPY header; row parsing expects the first data line at
19/// offset 0.
20pub fn trim_copy_data(data: &[u8]) -> &[u8] {
21    let start = data
22        .iter()
23        .position(|&b| !matches!(b, b'\n' | b'\r' | b' ' | b'\t'))
24        .unwrap_or(data.len());
25    &data[start..]
26}
27
28#[cfg(test)]
29mod tests {
30    use super::*;
31
32    #[test]
33    fn detects_copy_terminator() {
34        assert!(is_copy_data_block(b"1\tfoo\n2\tbar\n\\.\n"));
35        assert!(is_copy_data_block(b"1\tfoo\r\n\\.\r\n"));
36        assert!(!is_copy_data_block(b"INSERT INTO t VALUES (1);"));
37        assert!(!is_copy_data_block(b"1\tfoo\n"));
38    }
39
40    #[test]
41    fn trims_leading_whitespace_as_slice() {
42        assert_eq!(trim_copy_data(b"\n1\tfoo\n\\.\n"), b"1\tfoo\n\\.\n");
43        assert_eq!(trim_copy_data(b"\r\n\t 1\n"), b"1\n");
44        assert_eq!(trim_copy_data(b"1\n"), b"1\n");
45        assert_eq!(trim_copy_data(b"\n \t\r\n"), b"");
46        assert_eq!(trim_copy_data(b""), b"");
47    }
48}