Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

fix(autoindex): index SQL schema and routines as code (#2337) (#2342)

xerj-org55574993ef6b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 92cecdd5c..4e33643c0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -108,6 +108,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- `xerj autoindex` indexes `.sql` schema, migration, and routine files as
+ code. `CREATE TABLE` / `VIEW` / `FUNCTION` / `PROCEDURE` / `INDEX` /
+ `TRIGGER` / `TYPE` / `SCHEMA` / `SEQUENCE` become symbols, and the source
+ stays searchable. A comment, a quoted literal, a dollar-quoted body,
+ or an `INSERT`/`COPY` nested inside another statement is not a dump.
+ Those files used to be sniffed as an
+ empty SQL dump and skipped (`no records extracted`), which dropped
+ hand-written DDL such as a rule-engine script. A file with a top-level
+ `INSERT … VALUES` is still a row dump. A data-only `COPY … FROM stdin`
+ dump, which the row parser does not read, is skipped with that reason;
+ when the same file also contains schema statements, those statements are
+ indexed as code (#2337).
+
- A full process memtable budget now flushes instead of leaving `xerj autoindex`
on HTTP 429 until it gives up. The rejection requests a drain (largest
memtable first) rather than waiting for the next memory sample, and a
diff --git a/engine/crates/xerj-autoindex/Cargo.toml b/engine/crates/xerj-autoindex/Cargo.toml
index 706572acf..d4353452e 100644
--- a/engine/crates/xerj-autoindex/Cargo.toml
+++ b/engine/crates/xerj-autoindex/Cargo.toml
@@ -106,8 +106,9 @@ tree-sitter-elixir = "0.3"
# tree-sitter-language (core is a dev-dependency only), so it loads fine.
tree-sitter-clojure-orchard = "0.2"
tree-sitter-scheme = "0.24"
-# NOT tree-sitter-sql: 0.0.2 is immature (the issue itself says evaluate
-# first or defer) and `.sql` routing must not steal sqldump files — deferred.
+# `.sql` DDL is indexed as code by extract/sqlsrc.rs (statement scanner,
+# #2337). It is not a registry extension: claiming `.sql` would steal
+# sqldump files. tree-sitter-sql 0.0.2 is a different, abandoned crate.
tree-sitter-erlang = "0.20"
tree-sitter-ocaml = "0.25"
tree-sitter-zig = "1.1"
diff --git a/engine/crates/xerj-autoindex/src/extract/code.rs b/engine/crates/xerj-autoindex/src/extract/code.rs
index 5e07c030e..b7844aac7 100644
--- a/engine/crates/xerj-autoindex/src/extract/code.rs
+++ b/engine/crates/xerj-autoindex/src/extract/code.rs
@@ -350,6 +350,13 @@ pub fn extract(path: &Path, sn: &crate::sniff::Sniffed, sink: Sink) -> Result<Ex
.and_then(|e| e.to_str())
.unwrap_or("")
.to_ascii_lowercase();
+ // #2337: SQL source is code, but `.sql` is not a registry extension.
+ // A registry row would claim dumps in the sniffer before content is
+ // read. The DDL scanner runs only after sniff has ruled a dump out
+ // (or the dump extractor emitted nothing and the caller fell through).
+ if crate::sniff::is_sql_filename(named) {
+ return super::sqlsrc::extract(path, named, sn.gzip, sink);
+ }
let claimants: Vec<&LangDef> = registry()
.iter()
.filter(|d| d.exts.contains(&ext.as_str()))
@@ -3009,9 +3016,12 @@ mod tests {
}
// Deliberately NOT claimed, each for a stated reason: fixed-form
// Fortran would mis-parse under the free-form grammar; nim/crystal
- // have no usable published grammar; sql routing is deferred; `.sls`
- // is an R6RS library but also a SaltStack state file (YAML), and a
- // single-claimant extension is never content-probed; `.edn` is data.
+ // have no usable published grammar; `.sql` is indexed as code by
+ // the DDL scanner in `sqlsrc` only after the dump sniff (#2337) —
+ // a registry row would claim INSERT/COPY dumps before that sniff;
+ // `.sls` is an R6RS library but also a SaltStack state file (YAML),
+ // and a single-claimant extension is never content-probed; `.edn`
+ // is data.
for ext in ["f", "nim", "cr", "sql", "sls", "edn"] {
assert!(!is_code_ext(ext), "{ext} must stay unclaimed (see #295)");
}
diff --git a/engine/crates/xerj-autoindex/src/extract/mod.rs b/engine/crates/xerj-autoindex/src/extract/mod.rs
index 2ae4d0402..433b663ad 100644
--- a/engine/crates/xerj-autoindex/src/extract/mod.rs
+++ b/engine/crates/xerj-autoindex/src/extract/mod.rs
@@ -21,6 +21,7 @@ pub mod pdf;
pub mod pptx;
pub mod sqldump;
pub mod sqlite_x;
+pub mod sqlsrc;
pub mod txt;
pub mod unity;
pub mod xls;
@@ -366,7 +367,31 @@ pub fn extract(
sink,
),
Family::Sqlite => sqlite_x::extract(path, limit_bytes.map(|_| 500), sink),
- Family::SqlDump => sqldump::extract(path, sn.gzip, limit_bytes, sink),
+ Family::SqlDump => {
+ let stats = sqldump::extract(path, sn.gzip, limit_bytes, sink)?;
+ // #2337: COPY dumps and other row formats this parser does not
+ // read yield zero records, and `scan_file` then junks the whole
+ // file — schema included. A `.sql` file in that state is source
+ // when it has DDL, and an explicit skip when it is only row data.
+ if stats.records == 0
+ && stats.refusal.is_none()
+ && crate::sniff::is_sql_filename(sn.logical_name.as_deref().unwrap_or(path))
+ {
+ let alt = sqlsrc::extract(
+ path,
+ sn.logical_name.as_deref().unwrap_or(path),
+ sn.gzip,
+ sink,
+ )?;
+ if alt.records > 0 {
+ return Ok(alt);
+ }
+ let mut stats = stats;
+ stats.refusal = Some(sqlsrc::DATA_ONLY_DUMP_REASON.to_string());
+ return Ok(stats);
+ }
+ Ok(stats)
+ }
Family::Code => code::extract(path, sn, sink),
Family::UnityYaml => unity::extract_unity(path, sn.gzip, limit_bytes, sink),
Family::UnityMeta => unity::extract_meta(path, sn.gzip, sink),
diff --git a/engine/crates/xerj-autoindex/src/extract/sqlsrc.rs b/engine/crates/xerj-autoindex/src/extract/sqlsrc.rs
new file mode 100644
index 000000000..661cef6e2
--- /dev/null
+++ b/engine/crates/xerj-autoindex/src/extract/sqlsrc.rs
@@ -0,0 +1,734 @@
+//! SQL source — schema, migrations, and routines — indexed as code.
+//!
+//! `.sql` is also the extension of a data dump, so it is not a tree-sitter
+//! registry row: claiming the extension would run before the dump sniff and
+//! steal `INSERT`/`COPY` files (#295, #2337). Symbols are the names on
+//! `CREATE` statements. A file the row parser does not read (Postgres
+//! `COPY … FROM stdin`, or an `INSERT` the dump lexer skips) falls through
+//! here from [`super::sqldump`]; schema in that file is still indexed, and a
+//! file with no schema is refused with [`DATA_ONLY_DUMP_REASON`].
+
+use super::{ExtractStats, FieldOrigin, RawRecord, Sink};
+use crate::sniff::{sql_dump_has_rows, SqlLex};
+use anyhow::Result;
+use serde_json::{Map, Value};
+use std::io::Read;
+use std::path::Path;
+
+/// Stored file body. Past this, row data is not kept and the body is the
+/// DDL text only — a multi-gigabyte `COPY` must not become one document.
+const BODY_CAP: usize = 2 << 20;
+/// One statement is buffered only up to here. A bulk `INSERT` is classified
+/// from its head and the rest is discarded.
+const STMT_CAP: usize = 64 << 10;
+const CODE_CHARS: usize = 400;
+const IMPL_CAP: usize = 16 << 10;
+
+/// `scan_file` prints this instead of "no records extracted" when a `.sql`
+/// file is row data and nothing in it is schema.
+pub const DATA_ONLY_DUMP_REASON: &str = "SQL data-only dump: no schema statements to index; COPY ... FROM stdin row data is skipped, and INSERT rows are indexed only when the statement parses";
+
+struct SqlSym {
+ name: String,
+ kind: &'static str,
+ line: usize,
+ end_line: usize,
+ code: String,
+ impl_text: String,
+}
+
+enum Phase {
+ Sql,
+ Copy { at_bol: bool, idx: usize },
+}
+
+struct ScanOut {
+ symbols: Vec<SqlSym>,
+ saw_row_data: bool,
+ /// Full decoded text when the file fits in [`BODY_CAP`], otherwise the
+ /// DDL statements only.
+ body: String,
+}
+
+pub fn extract(path: &Path, logical: &Path, gzip: bool, sink: Sink) -> Result<ExtractStats> {
+ let reader = super::open_reader(path, gzip, None)?;
+ let scan = scan_sql(reader)?;
+ if scan.symbols.is_empty() && scan.saw_row_data {
+ return Ok(ExtractStats::default());
+ }
+ if scan.body.trim().is_empty() && scan.symbols.is_empty() {
+ return Ok(ExtractStats::default());
+ }
+ Ok(emit(logical, &scan, sink))
+}
+
+fn scan_sql(mut reader: impl Read) -> Result<ScanOut> {
+ let mut lex = SqlLex::default();
+ let mut phase = Phase::Sql;
+ let mut full: Vec<u8> = Vec::new();
+ let mut keep_full = true;
+ let mut stmt: Vec<u8> = Vec::new();
+ let mut keep_stmt = true;
+ let mut line: usize = 1;
+ let mut stmt_line: usize = 1;
+ let mut stmt_end_line: usize = 1;
+ let mut symbols = Vec::new();
+ let mut saw_row_data = false;
+ let mut ddl = String::new();
+ let mut buf = [0u8; 64 << 10];
+
+ loop {
+ let n = reader.read(&mut buf)?;
+ if n == 0 {
+ break;
+ }
+ for &b in &buf[..n] {
+ if keep_full {
+ if full.len() >= BODY_CAP {
+ keep_full = false;
+ full.clear();
+ } else {
+ full.push(b);
+ }
+ }
+ if let Phase::Copy { at_bol, idx } = &mut phase {
+ if b == b'\n' {
+ line += 1;
+ }
+ if copy_terminator(b, at_bol, idx) {
+ phase = Phase::Sql;
+ }
+ continue;
+ }
+
+ if stmt.is_empty() && b.is_ascii_whitespace() {
+ if b == b'\n' {
+ line += 1;
+ }
+ let mut ignored = [0u8; 2];
+ let _ = lex.feed(b, &mut ignored);
+ continue;
+ }
+ if stmt.is_empty() {
+ stmt_line = line;
+ stmt_end_line = line;
+ keep_stmt = true;
+ }
+ if keep_stmt {
+ if stmt.len() >= STMT_CAP {
+ keep_stmt = false;
+ } else {
+ stmt.push(b);
+ }
+ }
+ if b == b'\n' {
+ line += 1;
+ } else {
+ stmt_end_line = line;
+ }
+ let mut visible = [0u8; 2];
+ let step = lex.feed(b, &mut visible);
+ if step.end_stmt {
+ if take_statement(
+ &stmt,
+ stmt_line,
+ stmt_end_line,
+ &mut symbols,
+ &mut saw_row_data,
+ &mut ddl,
+ ) {
+ phase = Phase::Copy {
+ at_bol: true,
+ idx: 0,
+ };
+ }
+ stmt.clear();
+ keep_stmt = true;
+ }
+ }
+ }
+ if !stmt.is_empty() {
+ let _ = take_statement(
+ &stmt,
+ stmt_line,
+ stmt_end_line,
+ &mut symbols,
+ &mut saw_row_data,
+ &mut ddl,
+ );
+ }
+ // A `\.` with no trailing newline is still the end of COPY data.
+ let body = if keep_full {
+ String::from_utf8_lossy(&full).into_owned()
+ } else {
+ ddl
+ };
+ Ok(ScanOut {
+ symbols,
+ saw_row_data,
+ body,
+ })
+}
+
+/// `true` when the statement is `COPY … FROM stdin` and the following bytes
+/// are row data, not SQL.
+fn take_statement(
+ stmt: &[u8],
+ line: usize,
+ end_line: usize,
+ symbols: &mut Vec<SqlSym>,
+ saw_row_data: &mut bool,
+ ddl: &mut String,
+) -> bool {
+ let text = String::from_utf8_lossy(stmt);
+ let trimmed = text.trim();
+ if trimmed.is_empty() {
+ return false;
+ }
+ let head = trim_sql_noise(trimmed);
+ if head.is_empty() {
+ return false;
+ }
+ let copy = is_copy_stdin(head);
+ let insert = is_insert_values(head);
+ if copy || insert {
+ *saw_row_data = true;
+ return copy;
+ }
+ if let Some((kind, name)) = match_create(head) {
+ let code = cap_chars(trimmed, CODE_CHARS);
+ let impl_text = cap_bytes(trimmed, IMPL_CAP);
+ symbols.push(SqlSym {
+ name,
+ kind,
+ line,
+ end_line: end_line.max(line),
+ code,
+ impl_text,
+ });
+ }
+ if is_source_stmt(head) {
+ append_ddl(ddl, trimmed);
+ }
+ false
+}
+
+fn is_copy_stdin(head: &str) -> bool {
+ starts_with_kw(head, "copy") && sql_dump_has_rows(head.as_bytes())
+}
+
+fn is_insert_values(head: &str) -> bool {
+ starts_with_kw(head, "insert") && sql_dump_has_rows(head.as_bytes())
+}
+
+fn is_source_stmt(head: &str) -> bool {
+ let Some(word) = first_word(head) else {
+ return false;
+ };
+ matches!(
+ word.to_ascii_lowercase().as_str(),
+ "create" | "alter" | "drop" | "grant" | "revoke" | "comment" | "do"
+ )
+}
+
+fn first_word(s: &str) -> Option<&str> {
+ let s = s.trim_start();
+ if s.is_empty() {
+ return None;
+ }
+ let end = s
+ .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
+ .unwrap_or(s.len());
+ if end == 0 {
+ None
+ } else {
+ Some(&s[..end])
+ }
+}
+
+/// `true` when `b` finishes a `\.` terminator line.
+fn copy_terminator(b: u8, at_bol: &mut bool, idx: &mut usize) -> bool {
+ const END: &[u8] = b"\\.";
+ if *at_bol {
+ if *idx < END.len() && b == END[*idx] {
+ *idx += 1;
+ return false;
+ }
+ if *idx == END.len() && (b == b'\n' || b == b'\r') {
+ *idx = 0;
+ *at_bol = true;
+ return true;
+ }
+ *idx = 0;
+ if b == b'\n' {
+ return false;
+ }
+ *at_bol = false;
+ return false;
+ }
+ if b == b'\n' {
+ *at_bol = true;
+ *idx = 0;
+ }
+ false
+}
+
+fn append_ddl(ddl: &mut String, stmt: &str) {
+ if ddl.len() >= BODY_CAP {
+ return;
+ }
+ if !ddl.is_empty() {
+ ddl.push('\n');
+ }
+ let room = BODY_CAP.saturating_sub(ddl.len());
+ if stmt.len() <= room {
+ ddl.push_str(stmt);
+ } else {
+ let mut cut = room;
+ while cut > 0 && !stmt.is_char_boundary(cut) {
+ cut -= 1;
+ }
+ ddl.push_str(&stmt[..cut]);
+ }
+}
+
+fn trim_sql_noise(s: &str) -> &str {
+ let mut s = s.trim_start();
+ loop {
+ if let Some(rest) = s.strip_prefix("--") {
+ if let Some(i) = rest.find('\n') {
+ s = rest[i + 1..].trim_start();
+ continue;
+ }
+ return "";
+ }
+ if let Some(rest) = s.strip_prefix("/*") {
+ if let Some(i) = rest.find("*/") {
+ s = rest[i + 2..].trim_start();
+ continue;
+ }
+ return "";
+ }
+ return s;
+ }
+}
+
+fn starts_with_kw(s: &str, kw: &str) -> bool {
+ let s = trim_sql_noise(s);
+ if s.len() < kw.len() || !s[..kw.len()].eq_ignore_ascii_case(kw) {
+ return false;
+ }
+ s.as_bytes()
+ .get(kw.len())
+ .is_none_or(|b| !is_ident_byte(*b))
+}
+
+fn is_ident_byte(b: u8) -> bool {
+ b.is_ascii_alphanumeric() || b == b'_' || b == b'$'
+}
+
+struct Words<'a> {
+ s: &'a str,
+ i: usize,
+}
+
+impl<'a> Words<'a> {
+ fn new(s: &'a str) -> Self {
+ Self {
+ s: trim_sql_noise(s),
+ i: 0,
+ }
+ }
+
+ fn skip_ws(&mut self) {
+ let rest = &self.s[self.i..];
+ self.i += rest.len() - rest.trim_start().len();
+ }
+
+ fn eat(&mut self, kw: &str) -> bool {
+ self.skip_ws();
+ let rest = &self.s[self.i..];
+ if rest.len() >= kw.len()
+ && rest[..kw.len()].eq_ignore_ascii_case(kw)
+ && rest
+ .as_bytes()
+ .get(kw.len())
+ .is_none_or(|b| !is_ident_byte(*b))
+ {
+ self.i += kw.len();
+ true
+ } else {
+ false
+ }
+ }
+
+ fn rest(&mut self) -> &'a str {
+ self.skip_ws();
+ &self.s[self.i..]
+ }
+}
+
+fn match_create(stmt: &str) -> Option<(&'static str, String)> {
+ let mut w = Words::new(stmt);
+ if !w.eat("create") {
+ return None;
+ }
+ loop {
+ if w.eat("or") {
+ if !w.eat("replace") {
+ return None;
+ }
+ continue;
+ }
+ if w.eat("temp")
+ || w.eat("temporary")
+ || w.eat("unlogged")
+ || w.eat("unique")
+ || w.eat("materialized")
+ || w.eat("constraint")
+ || w.eat("global")
+ || w.eat("local")
+ {
+ continue;
+ }
+ break;
+ }
+ let kind = if w.eat("table") {
+ "table"
+ } else if w.eat("view") {
+ "view"
+ } else if w.eat("function") {
+ "function"
+ } else if w.eat("procedure") {
+ "procedure"
+ } else if w.eat("index") {
+ "index"
+ } else if w.eat("trigger") {
+ "trigger"
+ } else if w.eat("type") {
+ "type"
+ } else if w.eat("schema") {
+ "schema"
+ } else if w.eat("sequence") {
+ "sequence"
+ } else {
+ return None;
+ };
+ loop {
+ if w.eat("concurrently") {
+ continue;
+ }
+ if w.eat("if") {
+ let _ = w.eat("not");
+ let _ = w.eat("exists");
+ continue;
+ }
+ break;
+ }
+ let name = parse_qualified_name(w.rest())?;
+ if name.is_empty() || name.chars().count() > 200 {
+ return None;
+ }
+ Some((kind, name))
+}
+
+fn parse_qualified_name(s: &str) -> Option<String> {
+ let mut rest = s.trim_start();
+ let (name, next) = parse_ident(rest)?;
+ if name.is_empty() {
+ return None;
+ }
+ let mut last = name;
+ rest = next.trim_start();
+ while let Some(r) = rest.strip_prefix('.') {
+ rest = r.trim_start();
+ let (name, next) = parse_ident(rest)?;
+ if name.is_empty() {
+ return None;
+ }
+ last = name;
+ rest = next.trim_start();
+ }
+ Some(last)
+}
+
+fn parse_ident(s: &str) -> Option<(String, &str)> {
+ let mut chars = s.chars();
+ let c = chars.next()?;
+ match c {
+ '"' | '`' => {
+ let mut name = String::new();
+ let mut i = c.len_utf8();
+ while i < s.len() {
+ let ch = s[i..].chars().next()?;
+ let n = i + ch.len_utf8();
+ if ch == c {
+ if s[n..].starts_with(c) {
+ name.push(c);
+ i = n + c.len_utf8();
+ continue;
+ }
+ return Some((name, &s[n..]));
+ }
+ name.push(ch);
+ i = n;
+ }
+ None
+ }
+ '[' => {
+ let end = s.find(']')?;
+ Some((s[1..end].to_string(), &s[end + 1..]))
+ }
+ ch if ch.is_ascii_alphabetic() || ch == '_' => {
+ let end = s
+ .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$'))
+ .unwrap_or(s.len());
+ Some((s[..end].to_string(), &s[end..]))
+ }
+ _ => None,
+ }
+}
+
+fn cap_chars(s: &str, n: usize) -> String {
+ if s.chars().count() <= n {
+ s.to_string()
+ } else {
+ s.chars().take(n).collect()
+ }
+}
+
+fn cap_bytes(s: &str, n: usize) -> String {
+ if s.len() <= n {
+ return s.to_string();
+ }
+ let mut cut = n;
+ while cut > 0 && !s.is_char_boundary(cut) {
+ cut -= 1;
+ }
+ s[..cut].to_string()
+}
+
+/// Same record shape as `code::emit_code_doc`: one file document plus one
+/// document per declaration. `impl` is the statement itself, so a large file
+/// whose stored body dropped the `COPY` payload still cites the source line.
+fn emit(logical: &Path, scan: &ScanOut, sink: Sink) -> ExtractStats {
+ let mut stats = ExtractStats::default();
+ let title = logical
+ .file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or("source")
+ .to_string();
+ let mut fields = Map::new();
+ fields.insert("title".into(), Value::String(title.clone()));
+ fields.insert("language".into(), Value::String("sql".into()));
+ if !scan.symbols.is_empty() {
+ let mut seen = std::collections::HashSet::new();
+ let defs: Vec<String> = scan
+ .symbols
+ .iter()
+ .filter(|s| seen.insert((s.kind, s.name.as_str())))
+ .map(|s| format!("{} {}", s.kind, s.name))
+ .collect();
+ fields.insert("defs".into(), Value::String(defs.join("\n")));
+ let arr: Vec<Value> = scan
+ .symbols
+ .iter()
+ .map(|s| {
+ let mut m = Map::new();
+ m.insert("name".into(), Value::String(s.name.clone()));
+ m.insert("kind".into(), Value::String(s.kind.to_string()));
+ m.insert("line".into(), Value::Number((s.line as u64).into()));
+ m.insert("end_line".into(), Value::Number((s.end_line as u64).into()));
+ Value::Object(m)
+ })
+ .collect();
+ fields.insert("symbols".into(), Value::Array(arr));
+ fields.insert(
+ "symbol_count".into(),
+ Value::Number((scan.symbols.len() as u64).into()),
+ );
+ }
+ fields.insert("body".into(), Value::String(scan.body.clone()));
+ stats.records += 1;
+ if !sink(RawRecord {
+ fields,
+ locator: "code".into(),
+ group: None,
+ origin: FieldOrigin::Extractor,
+ }) {
+ return stats;
+ }
+
+ let mut emitted = std::collections::HashSet::new();
+ for s in &scan.symbols {
+ if s.code.is_empty() {
+ continue;
+ }
+ let locator = format!("code:{}:{}", s.line, s.name);
+ if !emitted.insert(locator.clone()) {
+ continue;
+ }
+ let mut sf = Map::new();
+ sf.insert("title".into(), Value::String(s.name.clone()));
+ sf.insert("path".into(), Value::String(title.clone()));
+ sf.insert("language".into(), Value::String("sql".into()));
+ sf.insert("name".into(), Value::String(s.name.clone()));
+ sf.insert("kind".into(), Value::String(s.kind.to_string()));
+ sf.insert("line".into(), Value::Number((s.line as u64).into()));
+ sf.insert("end_line".into(), Value::Number((s.end_line as u64).into()));
+ sf.insert("code".into(), Value::String(s.code.clone()));
+ if !s.impl_text.is_empty() {
+ sf.insert("impl".into(), Value::String(s.impl_text.clone()));
+ }
+ stats.records += 1;
+ if !sink(RawRecord {
+ fields: sf,
+ locator,
+ group: None,
+ origin: FieldOrigin::Extractor,
+ }) {
+ return stats;
+ }
+ }
+ stats
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::sniff::{self, Family};
+
+ fn write(dir: &Path, name: &str, body: &str) -> std::path::PathBuf {
+ let path = dir.join(name);
+ std::fs::write(&path, body).unwrap();
+ path
+ }
+
+ fn indexed(path: &Path) -> (crate::extract::ExtractStats, Vec<crate::extract::RawRecord>) {
+ let sn = sniff::sniff(path).unwrap();
+ let mut recs = Vec::new();
+ let stats = crate::extract::extract(path, &sn, None, &mut |r| {
+ recs.push(r);
+ true
+ })
+ .unwrap();
+ (stats, recs)
+ }
+
+ #[test]
+ fn ddl_symbols_include_qualified_and_quoted_names() {
+ let sql = "CREATE TABLE public.rules (id int);\n\
+ CREATE OR REPLACE VIEW \"Odd Name\" AS SELECT 1;\n\
+ CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_rules ON rules (id);\n\
+ CREATE SEQUENCE IF NOT EXISTS rules_id_seq;\n\
+ CREATE SCHEMA app;\n\
+ CREATE TYPE rule_status AS ENUM ('on');\n\
+ CREATE TRIGGER rules_touch AFTER INSERT ON rules FOR EACH ROW EXECUTE FUNCTION touch();\n";
+ let dir = tempfile::tempdir().unwrap();
+ let path = write(dir.path(), "schema.sql", sql);
+ let (stats, recs) = indexed(&path);
+ assert!(stats.refusal.is_none());
+ assert!(stats.records >= 7, "{stats:?}");
+ let defs = recs
+ .iter()
+ .find_map(|r| r.fields.get("defs").and_then(|v| v.as_str()))
+ .unwrap_or("");
+ for want in [
+ "table rules",
+ "view Odd Name",
+ "index idx_rules",
+ "sequence rules_id_seq",
+ "schema app",
+ "type rule_status",
+ "trigger rules_touch",
+ ] {
+ assert!(defs.contains(want), "missing {want} in {defs}");
+ }
+ }
+
+ #[test]
+ fn a_copy_dump_with_schema_indexes_the_table_and_skips_the_rows() {
+ let sql = "CREATE TABLE users (id int, email text);\n\
+ COPY users (id, email) FROM stdin;\n\
+ \\.\n\
+ CREATE INDEX idx_users_email ON users (email);\n";
+ let dir = tempfile::tempdir().unwrap();
+ let path = write(dir.path(), "dump.sql", sql);
+ let sn = sniff::sniff(&path).unwrap();
+ assert_eq!(sn.family, Family::SqlDump);
+ let (stats, recs) = indexed(&path);
+ assert!(stats.records > 0, "schema in a COPY dump must not be junk");
+ assert!(stats.refusal.is_none(), "{stats:?}");
+ let defs = recs
+ .iter()
+ .find_map(|r| r.fields.get("defs").and_then(|v| v.as_str()))
+ .unwrap_or("");
+ assert!(
+ defs.contains("table users") && defs.contains("index idx_users_email"),
+ "{defs}"
+ );
+ // The indexed body is the source we kept. Row text may remain when
+ // the file is small; the structured row fields must not.
+ assert!(
+ recs.iter().all(|r| r.fields.get("email").is_none()),
+ "COPY rows are not dump fields: {recs:?}"
+ );
+ }
+
+ #[test]
+ fn a_data_only_copy_dump_is_skipped_with_a_reason() {
+ let sql = "COPY users (id, email) FROM stdin;\n1\[email protected]\n\\.\n";
+ let dir = tempfile::tempdir().unwrap();
+ let path = write(dir.path(), "rows.sql", sql);
+ let sn = sniff::sniff(&path).unwrap();
+ assert_eq!(sn.family, Family::SqlDump);
+ let (stats, recs) = indexed(&path);
+ assert_eq!(stats.records, 0);
+ assert!(recs.is_empty());
+ assert_eq!(
+ stats.refusal.as_deref(),
+ Some(DATA_ONLY_DUMP_REASON),
+ "{stats:?}"
+ );
+ }
+
+ #[test]
+ fn an_insert_dump_still_yields_rows() {
+ let sql = "CREATE TABLE users (id int, name text);\n\
+ INSERT INTO users VALUES (1,'ann');\n";
+ let dir = tempfile::tempdir().unwrap();
+ let path = write(dir.path(), "dump.sql", sql);
+ let (stats, recs) = indexed(&path);
+ assert_eq!(stats.records, 1, "{recs:?}");
+ assert_eq!(recs[0].fields["name"], serde_json::json!("ann"));
+ }
+
+ #[test]
+ fn a_procedure_whose_body_inserts_is_a_function_symbol() {
+ let sql = "CREATE PROCEDURE seed_rules()\n\
+ BEGIN\n\
+ INSERT INTO rules VALUES (1);\n\
+ END;\n";
+ let dir = tempfile::tempdir().unwrap();
+ let path = write(dir.path(), "seed.sql", sql);
+ let sn = sniff::sniff(&path).unwrap();
+ // The INSERT is not dollar-quoted, so the probe may call this a dump.
+ // Either way the procedure has to be indexed, not junked.
+ let (stats, recs) = indexed(&path);
+ assert!(
+ stats.records > 0,
+ "family {:?} junked the procedure",
+ sn.family
+ );
+ let defs = recs
+ .iter()
+ .find_map(|r| r.fields.get("defs").and_then(|v| v.as_str()))
+ .unwrap_or("");
+ assert!(
+ defs.contains("procedure seed_rules"),
+ "{defs} family {:?}",
+ sn.family
+ );
+ }
+}
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index 8b42dda06..e9bf19350 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -4022,6 +4022,43 @@ mod clustering_key_tests {
assert_eq!(clusters.len(), 1, "{clusters:#?}");
}
+ /// #2337: a hand-written DDL file, including a routine whose body
+ /// inserts a row, is code. `scan_file` must not record it as junk.
+ #[test]
+ fn a_handwritten_sql_schema_is_code_not_junk() {
+ let dir = tempfile::tempdir().unwrap();
+ let body = "-- rule engine\n\
+ CREATE TABLE rules (\n\
+ id integer primary key,\n\
+ code text not null\n\
+ );\n\
+ CREATE OR REPLACE FUNCTION apply_slope(percent numeric)\n\
+ RETURNS text LANGUAGE plpgsql AS $$\n\
+ BEGIN\n\
+ INSERT INTO audit(note) VALUES ('slope');\n\
+ RETURN 'low';\n\
+ END;\n\
+ $$;\n";
+ let scanned = scan(dir.path(), "30_rule_engine.sql", body);
+ assert!(scanned.junk.is_none(), "DDL was junked: {:?}", scanned.junk);
+ assert_eq!(
+ scanned.sniffed.as_ref().map(|s| s.family),
+ Some(Family::Code)
+ );
+ let defs: Vec<String> = scanned
+ .sketches
+ .iter()
+ .filter_map(|s| s.fields.get("defs"))
+ .flat_map(|v| v.examples.iter().chain(v.raw_values.iter()).cloned())
+ .collect();
+ assert!(
+ defs.iter()
+ .any(|d| d.contains("table rules") && d.contains("function apply_slope")),
+ "defs={defs:?} junk={:?}",
+ scanned.junk
+ );
+ }
+
/// The other half: a data file's own column names ARE the key, so real
/// schemas still drive clustering.
#[test]
diff --git a/engine/crates/xerj-autoindex/src/sniff.rs b/engine/crates/xerj-autoindex/src/sniff.rs
index 507b41671..477ca15cf 100644
--- a/engine/crates/xerj-autoindex/src/sniff.rs
+++ b/engine/crates/xerj-autoindex/src/sniff.rs
@@ -232,8 +232,12 @@ pub fn sniff_with_name(content_path: &Path, logical_path: &Path) -> Result<Sniff
// otherwise fall through to text, because the prefix is schema only.
// One extra read, and only when the prefix already looks like DDL and
// the file continues. The scan stops at the first row statement.
+ // #2337: a `.sql` schema file is promoted to Code inside `sniff_bytes`.
+ // The same past-the-prefix row scan as #1984 still wins when the rest of
+ // the file is a real dump, so a long CREATE TABLE section followed by
+ // INSERT/COPY does not stay code.
if prefix.len() == PREFIX
- && matches!(s.family, Family::TxtLines | Family::TxtProse)
+ && matches!(s.family, Family::TxtLines | Family::TxtProse | Family::Code)
&& prefix_is_schema_ddl(&prefix)
&& file_contains_sql_row_data(content_path, gzip)
{
@@ -492,9 +496,34 @@ fn sniff_bytes(
out.family = txt_kind(&nonblank);
}
}
+ // #2337: `.sql` is not a tree-sitter extension. Claiming it before this
+ // point would mark every dump as code and the row extractor would never
+ // run. A file that survived the dump test is schema, a migration, or a
+ // routine — source, indexed as code.
+ if is_sql_filename(logical_path) && matches!(out.family, Family::TxtLines | Family::TxtProse) {
+ out.family = Family::Code;
+ }
Ok(out)
}
+/// `.sql`, or a gzipped `.sql.gz`. Case-insensitive. The dump-vs-source
+/// decision is content; this only says the name is SQL.
+pub(crate) fn is_sql_filename(path: &Path) -> bool {
+ let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
+ return false;
+ };
+ let name = name.as_bytes();
+ ends_with_ascii_ignore(name, b".sql") || ends_with_ascii_ignore(name, b".sql.gz")
+}
+
+fn ends_with_ascii_ignore(name: &[u8], suffix: &[u8]) -> bool {
+ name.len() >= suffix.len()
+ && name[name.len() - suffix.len()..]
+ .iter()
+ .zip(suffix)
+ .all(|(a, b)| a.to_ascii_lowercase() == *b)
+}
+
/// The label for the last-resort decode. Every byte maps to *something* in
/// windows-1252, so this never fails and therefore carries no evidence that
/// the bytes are text — the binary heuristics key off this exact string.
@@ -1645,15 +1674,16 @@ fn classify_structured(text: &str, nonblank: &[&str]) -> Option<Family> {
}
}
- // SQL dump (#1984). A dump carries rows: `INSERT INTO … VALUES (` or
- // Postgres `COPY … FROM stdin`. Schema migrations are DDL only
- // (`CREATE TABLE` / `ALTER TABLE` / `CREATE INDEX`) and the dump
- // extractor emits nothing for them, so `scan_file` junked the file
- // ("no records extracted") and the migration was unsearchable. DDL
- // alone returns None: the text fallback indexes it with line numbers,
- // and the CSV probe below does not read a trailing `;` as a delimiter.
- // Row data that starts past the sniff prefix is caught in
- // `sniff_with_name`, which keeps reading when this prefix is schema.
+ // SQL dump (#1984, #2337). A dump carries top-level row data:
+ // `INSERT INTO … VALUES (` or Postgres `COPY … FROM stdin`. Matches
+ // inside comments, quotes, or dollar-quoted routine bodies do not
+ // count — a migration that mentions INSERT, or a function whose body
+ // inserts a row, is source. The dump extractor emits nothing for DDL,
+ // so treating that file as a dump junked it ("no records extracted").
+ // DDL alone returns None. A `.sql` name is then promoted to code in
+ // `sniff_bytes`; the CSV probe below does not read a trailing `;` as
+ // a delimiter. Row data that starts past the sniff prefix is caught
+ // in `sniff_with_name`.
if sql_dump_has_rows(text.as_bytes()) {
return Some(Family::SqlDump);
}
@@ -1714,11 +1744,255 @@ fn scan_sql_row_data(mut reader: impl Read) -> bool {
}
}
-fn sql_dump_has_rows(bytes: &[u8]) -> bool {
+pub(crate) fn sql_dump_has_rows(bytes: &[u8]) -> bool {
let mut probe = SqlRowProbe::default();
probe.push(bytes) || probe.finish()
}
+/// One step of [`SqlLex::feed`]. `n` visible code bytes were written to the
+/// caller buffer. `end_stmt` is a `;` outside strings, comments, dollar
+/// quotes, and parentheses.
+pub(crate) struct SqlLexStep {
+ pub n: u8,
+ pub end_stmt: bool,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum SqlMode {
+ Code,
+ LineComment,
+ Block,
+ SQuote,
+ SQuoteEsc,
+ SQuoteEnd,
+ DQuote,
+ DQuoteEsc,
+ DQuoteEnd,
+ Tick,
+ TickEsc,
+ TickEnd,
+ DollarOpen,
+ Dollar,
+}
+
+/// Hides comments, quotes, and dollar-quoted bodies from the row-data probe,
+/// and tells a statement scanner where a top-level statement ends.
+///
+/// The probe used to match `INSERT INTO … VALUES (` anywhere in the bytes.
+/// A comment (`-- backfill: INSERT INTO t VALUES (1);`) or a PL/pgSQL body
+/// (`AS $$ … INSERT INTO audit VALUES (1); … $$`) then classified a schema
+/// file as a dump. The dump extractor emits no rows for that file, and
+/// `scan_file` junked it (#2337).
+pub(crate) struct SqlLex {
+ mode: SqlMode,
+ /// MySQL identifier quotes. Off for the row probe: a Markdown fence is
+ /// also backticks, and hiding them would miss `INSERT` inside a README
+ /// code block (#360). The statement scanner keeps them on.
+ mask_ticks: bool,
+ /// `-` or `/` in code, waiting for the second byte of `--` or `/*`.
+ hold: Option<u8>,
+ block_star: bool,
+ dollar_tag: Vec<u8>,
+ dollar_closer: Vec<u8>,
+ dollar_at: usize,
+ paren: i32,
+}
+
+impl Default for SqlLex {
+ fn default() -> Self {
+ Self {
+ mode: SqlMode::Code,
+ mask_ticks: true,
+ hold: None,
+ block_star: false,
+ dollar_tag: Vec::new(),
+ dollar_closer: Vec::new(),
+ dollar_at: 0,
+ paren: 0,
+ }
+ }
+}
+
+impl SqlLex {
+ pub(crate) fn feed(&mut self, b: u8, out: &mut [u8; 2]) -> SqlLexStep {
+ let mut n = 0usize;
+ let mut end_stmt = false;
+ // A held byte or an aborted `$` / quote is replayed by looping, not
+ // by recursion. Four steps covers hold-replay plus one abort.
+ for _ in 0..4 {
+ match self.mode {
+ SqlMode::LineComment => {
+ if b == b'\n' {
+ self.mode = SqlMode::Code;
+ }
+ break;
+ }
+ SqlMode::Block => {
+ if self.block_star {
+ self.block_star = false;
+ if b == b'/' {
+ self.mode = SqlMode::Code;
+ } else if b == b'*' {
+ self.block_star = true;
+ }
+ } else if b == b'*' {
+ self.block_star = true;
+ }
+ break;
+ }
+ SqlMode::SQuoteEsc | SqlMode::DQuoteEsc | SqlMode::TickEsc => {
+ self.mode = match self.mode {
+ SqlMode::SQuoteEsc => SqlMode::SQuote,
+ SqlMode::DQuoteEsc => SqlMode::DQuote,
+ _ => SqlMode::Tick,
+ };
+ break;
+ }
+ SqlMode::SQuote | SqlMode::DQuote | SqlMode::Tick => {
+ let (q, esc, end) = match self.mode {
+ SqlMode::DQuote => (b'"', SqlMode::DQuoteEsc, SqlMode::DQuoteEnd),
+ SqlMode::Tick => (b'`', SqlMode::TickEsc, SqlMode::TickEnd),
+ _ => (b'\'', SqlMode::SQuoteEsc, SqlMode::SQuoteEnd),
+ };
+ if b == b'\\' {
+ self.mode = esc;
+ } else if b == q {
+ self.mode = end;
+ }
+ break;
+ }
+ SqlMode::SQuoteEnd | SqlMode::DQuoteEnd | SqlMode::TickEnd => {
+ let (q, inside) = match self.mode {
+ SqlMode::DQuoteEnd => (b'"', SqlMode::DQuote),
+ SqlMode::TickEnd => (b'`', SqlMode::Tick),
+ _ => (b'\'', SqlMode::SQuote),
+ };
+ if b == q {
+ self.mode = inside;
+ break;
+ }
+ self.mode = SqlMode::Code;
+ continue;
+ }
+ SqlMode::Dollar => {
+ if self.dollar_at < self.dollar_closer.len()
+ && b == self.dollar_closer[self.dollar_at]
+ {
+ self.dollar_at += 1;
+ if self.dollar_at == self.dollar_closer.len() {
+ self.mode = SqlMode::Code;
+ self.dollar_at = 0;
+ }
+ } else if !self.dollar_closer.is_empty() && b == self.dollar_closer[0] {
+ self.dollar_at = 1;
+ } else {
+ self.dollar_at = 0;
+ }
+ break;
+ }
+ SqlMode::DollarOpen => {
+ if self.dollar_tag.is_empty() && b == b'$' {
+ self.dollar_closer = b"$$".to_vec();
+ self.dollar_at = 0;
+ self.mode = SqlMode::Dollar;
+ break;
+ }
+ if (self.dollar_tag.is_empty() && (b.is_ascii_alphabetic() || b == b'_'))
+ || (!self.dollar_tag.is_empty()
+ && self.dollar_tag.len() < 128
+ && (b.is_ascii_alphanumeric() || b == b'_'))
+ {
+ self.dollar_tag.push(b);
+ break;
+ }
+ if b == b'$' && !self.dollar_tag.is_empty() {
+ let mut closer = Vec::with_capacity(self.dollar_tag.len() + 2);
+ closer.push(b'$');
+ closer.append(&mut self.dollar_tag);
+ closer.push(b'$');
+ self.dollar_closer = closer;
+ self.dollar_at = 0;
+ self.mode = SqlMode::Dollar;
+ break;
+ }
+ // `$1` and other non-quotes. The `$` and the tag are not
+ // keywords; the current byte is real code.
+ self.dollar_tag.clear();
+ self.mode = SqlMode::Code;
+ continue;
+ }
+ SqlMode::Code => {
+ if let Some(h) = self.hold.take() {
+ if h == b'-' && b == b'-' {
+ self.mode = SqlMode::LineComment;
+ break;
+ }
+ if h == b'/' && b == b'*' {
+ self.mode = SqlMode::Block;
+ self.block_star = false;
+ break;
+ }
+ self.emit_visible(h, out, &mut n, &mut end_stmt);
+ continue;
+ }
+ if b == b'-' || b == b'/' {
+ self.hold = Some(b);
+ break;
+ }
+ if b == b'\'' {
+ self.mode = SqlMode::SQuote;
+ break;
+ }
+ if b == b'"' {
+ self.mode = SqlMode::DQuote;
+ break;
+ }
+ if b == b'`' && self.mask_ticks {
+ self.mode = SqlMode::Tick;
+ break;
+ }
+ if b == b'$' {
+ self.dollar_tag.clear();
+ self.mode = SqlMode::DollarOpen;
+ break;
+ }
+ self.emit_visible(b, out, &mut n, &mut end_stmt);
+ break;
+ }
+ }
+ }
+ SqlLexStep {
+ n: n as u8,
+ end_stmt,
+ }
+ }
+
+ /// A `-` or `/` held at EOF is code, not the start of a comment.
+ pub(crate) fn flush_hold(&mut self) -> Option<u8> {
+ if self.mode == SqlMode::Code {
+ self.hold.take()
+ } else {
+ self.hold = None;
+ None
+ }
+ }
+
+ fn emit_visible(&mut self, b: u8, out: &mut [u8; 2], n: &mut usize, end_stmt: &mut bool) {
+ if *n >= out.len() {
+ return;
+ }
+ if b == b'(' {
+ self.paren = self.paren.saturating_add(1);
+ } else if b == b')' {
+ self.paren = self.paren.saturating_sub(1);
+ } else if b == b';' && self.paren == 0 {
+ *end_stmt = true;
+ }
+ out[*n] = b;
+ *n += 1;
+ }
+}
+
fn is_sql_ident(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'_'
}
@@ -1744,6 +2018,14 @@ struct SqlRowProbe {
stdin_at: u8,
/// `STDIN` letters are complete; the next byte decides the boundary.
stdin_done: bool,
+ /// The next identifier is the first word of a statement. `INSERT` /
+ /// `COPY` count only there: a routine body (`BEGIN INSERT … END`) is
+ /// not a dump (#2337).
+ at_stmt: bool,
+ /// The current statement opened with `INSERT`.
+ stmt_insert: bool,
+ /// Comments, quotes, and dollar quotes are not row data (#2337).
+ lex: SqlLex,
}
const SQL_ROW_WIN: usize = 96;
@@ -1759,18 +2041,45 @@ impl Default for SqlRowProbe {
from_ws: false,
stdin_at: 0,
stdin_done: false,
+ at_stmt: true,
+ stmt_insert: false,
+ // Backticks stay visible. ``` fences in a README are not MySQL
+ // identifier quotes; masking them hides the INSERT the dump
+ // sniff has to see (#360).
+ lex: SqlLex {
+ mask_ticks: false,
+ ..SqlLex::default()
+ },
}
}
}
impl SqlRowProbe {
fn push(&mut self, chunk: &[u8]) -> bool {
- chunk.iter().any(|&b| self.push_byte(b))
+ chunk.iter().any(|&b| self.feed(b))
}
/// EOF is a word boundary, so a statement that ends on `STDIN` still hits.
fn finish(&mut self) -> bool {
- self.push_byte(b'\n')
+ let flushed = self.lex.flush_hold().is_some_and(|b| self.push_byte(b));
+ flushed || self.push_byte(b'\n')
+ }
+
+ fn feed(&mut self, b: u8) -> bool {
+ let mut buf = [0u8; 2];
+ let step = self.lex.feed(b, &mut buf);
+ let hit = (0..step.n as usize).any(|i| self.push_byte(buf[i]));
+ if step.end_stmt {
+ self.at_stmt = true;
+ self.stmt_insert = false;
+ self.seen_copy = false;
+ self.seen_insert_into = false;
+ self.values_ws = false;
+ self.from_ws = false;
+ self.stdin_at = 0;
+ self.stdin_done = false;
+ }
+ hit
}
fn push_byte(&mut self, b: u8) -> bool {
@@ -1812,6 +2121,14 @@ impl SqlRowProbe {
}
if boundary && self.win.last().is_some_and(|c| is_sql_ident(*c)) {
+ // The first word decides whether this statement can be row data.
+ // `CREATE PROCEDURE … INSERT INTO t VALUES (1)` is still DDL.
+ if self.at_stmt {
+ self.at_stmt = false;
+ self.stmt_insert = self.ends_with_word(b"INSERT");
+ self.seen_copy = self.ends_with_word(b"COPY");
+ self.seen_insert_into = false;
+ }
if self.seen_insert_into && self.ends_with_word(b"VALUES") {
if u == b'(' {
return true;
@@ -1823,12 +2140,13 @@ impl SqlRowProbe {
if self.seen_copy && self.ends_with_word(b"FROM") && u.is_ascii_whitespace() {
self.from_ws = true;
}
- if self.ends_with_word(b"INTO") && self.win_is_insert_into() {
+ if self.stmt_insert && self.ends_with_word(b"INTO") && self.win_is_insert_into() {
self.seen_insert_into = true;
}
- if self.ends_with_word(b"COPY") {
- self.seen_copy = true;
- }
+ } else if self.at_stmt && boundary && !u.is_ascii_whitespace() {
+ self.at_stmt = false;
+ self.stmt_insert = false;
+ self.seen_copy = false;
}
self.win.push(u);
@@ -3984,11 +4302,13 @@ mod tests {
);
}
- /// #1984: a schema migration is DDL with no row data. The dump extractor
- /// emits nothing for it, and `scan_file` then junks the file, so the
- /// column definition never becomes searchable.
+ /// #1984 / #2337: a schema migration is DDL with no row data. The dump
+ /// extractor emits nothing for it, and `scan_file` then junks the file.
+ /// Content classification stays text (so a non-`.sql` name is not forced
+ /// into the code family). A `.sql` name is indexed as code: the table is
+ /// a symbol and the column text is in the body.
#[test]
- fn schema_only_sql_migration_is_text_not_an_empty_dump() {
+ fn schema_only_sql_migration_is_code_not_an_empty_dump() {
let migration = "-- add users\n\
CREATE TABLE users (\n\
id INTEGER PRIMARY KEY,\n\
@@ -3999,28 +4319,29 @@ mod tests {
ALTER TABLE users ADD COLUMN name TEXT;\n\
\n\
CREATE INDEX idx_users_email ON users (email);\n";
- assert_eq!(
+ assert_ne!(
classify(migration),
- Family::TxtLines,
- "DDL with no INSERT/COPY is source text, not a dump"
+ Family::SqlDump,
+ "DDL with no INSERT/COPY is not a dump"
);
// One statement per line, every line ending in `;`. That shape is a
- // consistent `;`-delimited "CSV"; it must still be text.
+ // consistent `;`-delimited "CSV"; it must still not be a dump.
let one_liners = "CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT NOT NULL);\n\
ALTER TABLE users ADD COLUMN name TEXT;\n\
CREATE INDEX idx_users_email ON users (email);\n";
- let one_line_family = classify(one_liners);
- assert!(
- matches!(one_line_family, Family::TxtLines | Family::TxtProse),
- "semicolon-terminated DDL classified {one_line_family:?}"
+ assert_ne!(
+ classify(one_liners),
+ Family::SqlDump,
+ "semicolon-terminated DDL classified {:?}",
+ classify(one_liners)
);
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("001_users.sql");
std::fs::write(&path, migration).unwrap();
let sn = sniff(&path).unwrap();
- assert_eq!(sn.family, Family::TxtLines);
+ assert_eq!(sn.family, Family::Code);
let mut recs = Vec::new();
let stats = crate::extract::extract(&path, &sn, None, &mut |r| {
recs.push(r);
@@ -4033,13 +4354,78 @@ mod tests {
);
assert!(
recs.iter().any(|r| {
- r.fields
- .get("text")
- .and_then(|v| v.as_str())
- .is_some_and(|s| s.contains("email"))
- && r.fields.get("start_line").is_some()
+ r.fields.get("language").and_then(|v| v.as_str()) == Some("sql")
+ && r.fields
+ .get("defs")
+ .and_then(|v| v.as_str())
+ .is_some_and(|s| {
+ s.contains("table users") && s.contains("index idx_users_email")
+ })
+ && r.fields
+ .get("body")
+ .and_then(|v| v.as_str())
+ .is_some_and(|s| s.contains("email"))
+ }),
+ "the column definition must be searchable as code: {recs:?}"
+ );
+ assert!(
+ recs.iter().any(|r| {
+ r.fields.get("name").and_then(|v| v.as_str()) == Some("users")
+ && r.fields.get("kind").and_then(|v| v.as_str()) == Some("table")
+ && r.fields.get("line").is_some()
}),
- "the column definition must be searchable with a line number: {recs:?}"
+ "the table is its own declaration: {recs:?}"
+ );
+ }
+
+ /// #2337: a comment or a routine body that mentions `INSERT`/`COPY` is
+ /// not a dump. The rule-engine file in the field report is this shape.
+ #[test]
+ fn sql_routine_and_comment_inserts_are_code_not_junk() {
+ let rule = "-- backfill: INSERT INTO rules VALUES (1);\n\
+ CREATE TABLE rules (\n\
+ id integer primary key,\n\
+ code text not null\n\
+ );\n\
+ CREATE OR REPLACE FUNCTION apply_slope(percent numeric)\n\
+ RETURNS text LANGUAGE plpgsql AS $$\n\
+ BEGIN\n\
+ INSERT INTO audit(note) VALUES ('slope');\n\
+ RETURN 'low';\n\
+ END;\n\
+ $$;\n";
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("30_rule_engine.sql");
+ std::fs::write(&path, rule).unwrap();
+ let sn = sniff(&path).unwrap();
+ assert_eq!(
+ sn.family,
+ Family::Code,
+ "routine DDL classified {:?}",
+ sn.family
+ );
+ let mut recs = Vec::new();
+ let stats = crate::extract::extract(&path, &sn, None, &mut |r| {
+ recs.push(r);
+ true
+ })
+ .unwrap();
+ assert!(stats.records > 0, "a routine file must not be junked");
+ let defs = recs
+ .iter()
+ .find_map(|r| r.fields.get("defs").and_then(|v| v.as_str()))
+ .unwrap_or("");
+ assert!(
+ defs.contains("table rules") && defs.contains("function apply_slope"),
+ "{defs}"
+ );
+ let body = recs
+ .iter()
+ .find_map(|r| r.fields.get("body").and_then(|v| v.as_str()))
+ .unwrap_or("");
+ assert!(
+ body.contains("apply_slope") && body.contains("'low'"),
+ "{body}"
);
}
@@ -4113,8 +4499,9 @@ mod tests {
let schema = dir.path().join("schema.sql");
std::fs::write(&schema, &body).unwrap();
let schema_sn = sniff(&schema).unwrap();
- assert!(
- matches!(schema_sn.family, Family::TxtLines | Family::TxtProse),
+ assert_eq!(
+ schema_sn.family,
+ Family::Code,
"schema past the prefix classified {:?}",
schema_sn.family
);
@@ -4148,6 +4535,8 @@ mod tests {
"COPY users (id, name) FROM stdin;",
"COPY public.users FROM STDIN",
"INSERT\nINTO\nt\nVALUES\n(1)",
+ // #360: a README fence is backticks, not a MySQL identifier quote.
+ "# doc\n\n```sql\nCREATE TABLE t (id int);\nINSERT INTO t VALUES (1);\n```\n",
];
// The opener and the tuple can be far apart: a wide column list, or
// pg_dump's schema section before the first COPY.
@@ -4184,12 +4573,32 @@ mod tests {
"COPYRIGHT notice; FROM stdin;",
"INSERT INTO t VALUES 1;",
"REINSERT INTO t VALUES (1);",
+ "-- INSERT INTO t VALUES (1);\nCREATE TABLE t (a int);",
+ "/* COPY t FROM stdin; */\nCREATE TABLE t (a int);",
+ "CREATE FUNCTION f() AS $$\nBEGIN\n INSERT INTO t VALUES (1);\nEND;\n$$;",
+ "CREATE FUNCTION f() AS $body$\n INSERT INTO t VALUES (1);\n$body$;",
+ "CREATE PROCEDURE p() BEGIN INSERT INTO t VALUES (1); END;",
+ "SELECT 'INSERT INTO t VALUES (1)';",
] {
assert!(
!sql_dump_has_rows(sample.as_bytes()),
"false hit on {sample:?}"
);
}
+ // The same INSERT after the routine is a real dump, even when the
+ // opening `$` of the dollar quote is the last byte of a chunk.
+ let mixed = "CREATE FUNCTION f() AS $$\n INSERT INTO t VALUES (1);\n$$;\n\
+ INSERT INTO real_rows VALUES (2);\n";
+ assert!(
+ sql_dump_has_rows(mixed.as_bytes()),
+ "top-level INSERT after a routine must stay a dump"
+ );
+ let bytes = mixed.as_bytes();
+ let dollar = mixed.find('$').unwrap();
+ let mut probe = SqlRowProbe::default();
+ let hit =
+ probe.push(&bytes[..dollar + 1]) || probe.push(&bytes[dollar + 1..]) || probe.finish();
+ assert!(hit, "dollar quote split across a chunk hid a later INSERT");
}
/// #1142 class 1: markdown opening with an HTML fragment (Hugo front-matter