Skip to main content

sql_splitter/schema/
build.rs

1//! Shared "stream a SQL file into a [`Schema`]" helper.
2//!
3//! Several commands (diff, graph, order, redact, sample, shard) need a schema
4//! extracted from a dump's DDL before doing their real work. This module owns
5//! that pass so every consumer gets identical CREATE TABLE / ALTER TABLE /
6//! CREATE INDEX coverage instead of hand-rolling (and subtly diverging on)
7//! the same loop.
8
9use super::{Schema, SchemaBuilder};
10use crate::parser::{determine_buffer_size, Parser, SqlDialect, StatementType};
11use crate::splitter::open_input_opt_progress;
12use std::path::Path;
13
14impl SchemaBuilder {
15    /// Feed an already-classified statement into the builder.
16    ///
17    /// Non-DDL statement types are ignored, so callers that classify
18    /// statements for their own routing can pass everything through.
19    pub fn ingest(&mut self, stmt_type: StatementType, sql: &str) {
20        match stmt_type {
21            StatementType::CreateTable => {
22                self.parse_create_table(sql);
23            }
24            StatementType::AlterTable => {
25                self.parse_alter_table(sql);
26            }
27            StatementType::CreateIndex => {
28                self.parse_create_index(sql);
29            }
30            _ => {}
31        }
32    }
33
34    /// Classify a raw statement and feed it into the builder if it is DDL.
35    pub fn ingest_statement(&mut self, stmt: &[u8], dialect: SqlDialect) {
36        let (stmt_type, _table_name) = Parser::<&[u8]>::parse_statement_with_dialect(stmt, dialect);
37
38        if matches!(
39            stmt_type,
40            StatementType::CreateTable | StatementType::AlterTable | StatementType::CreateIndex
41        ) {
42            self.ingest(stmt_type, &String::from_utf8_lossy(stmt));
43        }
44    }
45}
46
47impl Schema {
48    /// Build a [`Schema`] by streaming the DDL statements of a SQL file.
49    ///
50    /// Opens `path` via [`open_input_opt_progress`], so all supported
51    /// compression formats (including zip archives) are handled
52    /// transparently. When `progress_fn` is `Some`, it receives cumulative
53    /// raw bytes read from disk.
54    pub fn from_sql_file(
55        path: &Path,
56        dialect: SqlDialect,
57        progress_fn: Option<Box<dyn Fn(u64)>>,
58    ) -> anyhow::Result<Schema> {
59        let file_size = std::fs::metadata(path)?.len();
60        let buffer_size = determine_buffer_size(file_size);
61        let reader = open_input_opt_progress(path, progress_fn)?;
62
63        let mut parser = Parser::with_dialect(reader, buffer_size, dialect);
64        let mut builder = SchemaBuilder::new();
65
66        while let Some(stmt) = parser.read_statement()? {
67            builder.ingest_statement(&stmt, dialect);
68        }
69
70        Ok(builder.build())
71    }
72}