Skip to main content

hawdb_executor/
load_csv.rs

1// Copyright 2026 Nowledge
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! `LOAD CSV` file access policy and record-to-row conversion.
16//!
17//! Files are read only beneath an explicitly configured import directory.
18//! Records are streamed through a fixed-size buffer; no plan or cache retains
19//! a resolved location or any file contents.
20
21mod reader;
22#[cfg(test)]
23mod tests;
24
25pub use reader::{CsvField, CsvRecordReader, CSV_READ_BUFFER_BYTES};
26
27use hawdb_core::{HawDBError, Result, Value};
28use hawdb_plan_cypher::{CsvLocation, LoadCsvSource};
29use std::collections::BTreeMap;
30use std::fs::File;
31use std::io::Read;
32use std::path::{Path, PathBuf};
33
34/// Resource bounds for one `LOAD CSV` source.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub struct CsvImportLimits {
37    /// Maximum bytes read from one file, checked before opening against the
38    /// file length and again while streaming.
39    pub max_file_bytes: u64,
40    /// Maximum field bytes in one record, excluding quotes and separators.
41    pub max_record_bytes: usize,
42    /// Maximum fields in one record, including the header record.
43    pub max_fields_per_record: usize,
44}
45
46impl Default for CsvImportLimits {
47    fn default() -> Self {
48        Self {
49            max_file_bytes: 4 * 1024 * 1024 * 1024,
50            max_record_bytes: 4 * 1024 * 1024,
51            max_fields_per_record: 4096,
52        }
53    }
54}
55
56/// The directory `LOAD CSV` may read from, and its per-file limits.
57///
58/// Without a policy, `LOAD CSV` is refused. With one, the canonical path of
59/// every source, after resolving `..` components and symbolic links, must be
60/// a regular file inside the canonical import root.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct CsvImportPolicy {
63    root: PathBuf,
64    limits: CsvImportLimits,
65}
66
67impl CsvImportPolicy {
68    pub fn new(root: impl Into<PathBuf>, limits: CsvImportLimits) -> Self {
69        Self {
70            root: root.into(),
71            limits,
72        }
73    }
74
75    pub fn root(&self) -> &Path {
76        &self.root
77    }
78
79    pub fn limits(&self) -> CsvImportLimits {
80        self.limits
81    }
82
83    /// Resolves `location` to a canonical file path inside the import root.
84    ///
85    /// Errors that depend only on the statement are `Semantic`: a malformed
86    /// or non-local location and a location outside the import directory
87    /// (after resolving symbolic links, or lexically when the target does not
88    /// exist). Filesystem conditions observed at run time are `Execution`: an
89    /// import root or source that cannot be accessed.
90    pub fn resolve(&self, location: &str) -> Result<PathBuf> {
91        let root = std::fs::canonicalize(&self.root).map_err(|error| {
92            HawDBError::or_stop(&error, || {
93                HawDBError::Execution(format!(
94                    "LOAD CSV import root '{}' cannot be resolved: {error}",
95                    self.root.display()
96                ))
97            })
98        })?;
99        if !root.is_dir() {
100            return Err(HawDBError::Execution(format!(
101                "LOAD CSV import root '{}' is not a directory",
102                root.display()
103            )));
104        }
105        let path = local_path(location)?;
106        let path = if path.is_absolute() {
107            path
108        } else {
109            root.join(path)
110        };
111        let canonical = std::fs::canonicalize(&path).map_err(|error| {
112            if lexically_outside(&path, &root, &self.root) {
113                outside_root(location)
114            } else {
115                HawDBError::Execution(format!("LOAD CSV cannot access '{location}': {error}"))
116            }
117        })?;
118        if !canonical.starts_with(&root) {
119            return Err(outside_root(location));
120        }
121        Ok(canonical)
122    }
123
124    /// Opens `source` for streaming after resolving and validating its location.
125    ///
126    /// The source must be a regular file before it is opened: opening a FIFO
127    /// or device could block or never end. The opened handle is checked again
128    /// for a file replaced between the two system calls.
129    pub fn open(
130        &self,
131        source: &LoadCsvSource,
132        parameters: &BTreeMap<String, Value>,
133    ) -> Result<CsvRows<File>> {
134        let location = source_location(source, parameters)?;
135        let path = self.resolve(location)?;
136        let inspect = |metadata: std::io::Result<std::fs::Metadata>| {
137            let metadata = metadata.map_err(|error| {
138                HawDBError::or_stop(&error, || {
139                    HawDBError::Execution(format!("LOAD CSV cannot inspect '{location}': {error}"))
140                })
141            })?;
142            if !metadata.is_file() {
143                return Err(HawDBError::Execution(format!(
144                    "LOAD CSV source '{location}' is not a regular file"
145                )));
146            }
147            if metadata.len() > self.limits.max_file_bytes {
148                return Err(HawDBError::Execution(format!(
149                    "LOAD CSV source '{location}' has {} bytes, exceeding max_file_bytes {}",
150                    metadata.len(),
151                    self.limits.max_file_bytes
152                )));
153            }
154            Ok(())
155        };
156        inspect(std::fs::metadata(&path))?;
157        let file = File::open(&path).map_err(|error| {
158            HawDBError::or_stop(&error, || {
159                HawDBError::Execution(format!("LOAD CSV cannot open '{location}': {error}"))
160            })
161        })?;
162        inspect(file.metadata())?;
163        CsvRows::new(file, source, self.limits)
164    }
165}
166
167fn outside_root(location: &str) -> HawDBError {
168    HawDBError::Semantic(format!(
169        "LOAD CSV source '{location}' is outside the configured import directory"
170    ))
171}
172
173/// Whether `path`, with `.` and `..` applied lexically, lies outside both the
174/// canonical and the configured import root. Used only for a target that
175/// cannot be canonicalized, so a missing file outside the root reports the
176/// policy violation rather than its absence.
177fn lexically_outside(path: &Path, canonical_root: &Path, configured_root: &Path) -> bool {
178    let normalize = |path: &Path| {
179        let mut normalized = PathBuf::new();
180        for component in path.components() {
181            match component {
182                std::path::Component::CurDir => {}
183                std::path::Component::ParentDir => {
184                    normalized.pop();
185                }
186                component => normalized.push(component),
187            }
188        }
189        normalized
190    };
191    let path = normalize(path);
192    let configured = std::path::absolute(configured_root)
193        .map(|root| normalize(&root))
194        .ok();
195    !path.starts_with(canonical_root)
196        && configured.is_none_or(|configured| !path.starts_with(configured))
197}
198
199/// Opens a `LOAD CSV` source, refusing when no import policy is configured.
200pub fn open_load_csv(
201    policy: Option<&CsvImportPolicy>,
202    source: &LoadCsvSource,
203    parameters: &BTreeMap<String, Value>,
204) -> Result<CsvRows<File>> {
205    policy
206        .ok_or_else(|| {
207            HawDBError::Semantic(
208                "LOAD CSV is disabled: set DatabaseConfig::csv_import_root to an import directory"
209                    .to_string(),
210            )
211        })?
212        .open(source, parameters)
213}
214
215fn source_location<'a>(
216    source: &'a LoadCsvSource,
217    parameters: &'a BTreeMap<String, Value>,
218) -> Result<&'a str> {
219    match &source.location {
220        CsvLocation::Literal(location) => Ok(location),
221        CsvLocation::Parameter(name) => match parameters.get(name) {
222            Some(Value::String(location)) => Ok(location),
223            Some(_) => Err(HawDBError::Semantic(format!(
224                "LOAD CSV source parameter '${name}' must be a string"
225            ))),
226            None => Err(HawDBError::Semantic(format!("missing parameter '${name}'"))),
227        },
228    }
229}
230
231/// Converts a `file:` URL or plain path to a filesystem path. `file:` URL
232/// paths are relative to the import directory, as in Neo4j. Every other URL
233/// scheme, including `http` and `https`, is refused.
234fn local_path(location: &str) -> Result<PathBuf> {
235    if location.is_empty() || location.contains('\0') {
236        return Err(HawDBError::Semantic(
237            "LOAD CSV source must be a non-empty file path".to_string(),
238        ));
239    }
240    let Some(scheme) = url_scheme(location) else {
241        return Ok(PathBuf::from(location));
242    };
243    if !scheme.eq_ignore_ascii_case("file") {
244        return Err(HawDBError::Semantic(format!(
245            "LOAD CSV supports only local files; '{scheme}' URLs are not supported"
246        )));
247    }
248    let rest = &location[scheme.len() + 1..];
249    let path = if let Some(authority_path) = rest.strip_prefix("//") {
250        let (host, path) = authority_path
251            .find('/')
252            .map_or((authority_path, ""), |index| authority_path.split_at(index));
253        if !host.is_empty() && !host.eq_ignore_ascii_case("localhost") {
254            return Err(HawDBError::Semantic(format!(
255                "LOAD CSV file URL host '{host}' is not supported; use file:///path relative to the import directory"
256            )));
257        }
258        path
259    } else {
260        rest
261    };
262    if path.contains(['?', '#']) {
263        return Err(HawDBError::Semantic(
264            "LOAD CSV file URLs must not contain a query or fragment".to_string(),
265        ));
266    }
267    if !path.starts_with('/') {
268        return Err(HawDBError::Semantic(
269            "LOAD CSV file URLs must have the form file:///path".to_string(),
270        ));
271    }
272    let decoded = percent_decode(path)?;
273    // Like Neo4j, `file:///x.csv` names `x.csv` inside the import directory;
274    // the URL path is never an absolute filesystem path.
275    Ok(PathBuf::from(decoded.trim_start_matches('/')))
276}
277
278/// Returns the URL scheme when `location` starts with `scheme:`. A single
279/// letter is a Windows drive, not a scheme.
280fn url_scheme(location: &str) -> Option<&str> {
281    let (scheme, _) = location.split_once(':')?;
282    let mut bytes = scheme.bytes();
283    let first = bytes.next()?;
284    (first.is_ascii_alphabetic()
285        && scheme.len() > 1
286        && bytes.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'-' | b'.')))
287    .then_some(scheme)
288}
289
290fn percent_decode(text: &str) -> Result<String> {
291    let bytes = text.as_bytes();
292    let mut decoded = Vec::with_capacity(bytes.len());
293    let mut index = 0;
294    while index < bytes.len() {
295        if bytes[index] == b'%' {
296            let hex = text
297                .get(index + 1..index + 3)
298                .and_then(|hex| u8::from_str_radix(hex, 16).ok())
299                .ok_or_else(|| {
300                    HawDBError::Semantic("LOAD CSV file URL has an invalid percent escape".into())
301                })?;
302            if hex == 0 {
303                return Err(HawDBError::Semantic(
304                    "LOAD CSV file URL must not contain NUL".to_string(),
305                ));
306            }
307            decoded.push(hex);
308            index += 3;
309        } else {
310            decoded.push(bytes[index]);
311            index += 1;
312        }
313    }
314    String::from_utf8(decoded)
315        .map_err(|_| HawDBError::Semantic("LOAD CSV file URL is not valid UTF-8".to_string()))
316}
317
318/// Streams the rows `LOAD CSV` binds to its variable.
319///
320/// Without headers a row is a list of strings. With headers it is a map from
321/// each header to the field in the same position. An empty unquoted field
322/// and a field missing from a short record are `NULL`; a quoted empty field
323/// is the empty string. Fields beyond the header count are ignored.
324pub struct CsvRows<R> {
325    reader: CsvRecordReader<R>,
326    headers: Option<Vec<String>>,
327    with_headers: bool,
328}
329
330impl<R: Read> CsvRows<R> {
331    pub fn new(input: R, source: &LoadCsvSource, limits: CsvImportLimits) -> Result<Self> {
332        Ok(Self {
333            reader: CsvRecordReader::new(input, source.field_terminator, limits)?,
334            headers: None,
335            with_headers: source.with_headers,
336        })
337    }
338
339    pub fn next_row(&mut self) -> Result<Option<Value>> {
340        if self.with_headers && self.headers.is_none() {
341            let Some(header) = self.reader.next_record()? else {
342                return Ok(None);
343            };
344            let mut seen = std::collections::BTreeSet::new();
345            let headers = header
346                .into_iter()
347                .map(|name| {
348                    let name = name.unwrap_or_default();
349                    if !seen.insert(name.clone()) {
350                        return Err(HawDBError::Execution(format!(
351                            "LOAD CSV header repeats column '{name}'"
352                        )));
353                    }
354                    Ok(name)
355                })
356                .collect::<Result<Vec<_>>>()?;
357            self.headers = Some(headers);
358        }
359        let Some(record) = self.reader.next_record()? else {
360            return Ok(None);
361        };
362        Ok(Some(match &self.headers {
363            None => Value::List(record.into_iter().map(field_value).collect()),
364            Some(headers) => {
365                let mut fields = record.into_iter();
366                Value::Map(
367                    headers
368                        .iter()
369                        .map(|name| (name.clone(), fields.next().map_or(Value::Null, field_value)))
370                        .collect(),
371                )
372            }
373        }))
374    }
375
376    /// Data records returned so far, excluding a header record.
377    pub fn rows_read(&self) -> u64 {
378        self.reader
379            .records()
380            .saturating_sub(u64::from(self.headers.is_some()))
381    }
382}
383
384fn field_value(field: CsvField) -> Value {
385    field.map_or(Value::Null, Value::String)
386}