use std::sync::OnceLock;
use indexmap::IndexMap;
use regex::{Match, Regex};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::error::{Result, SqlError};
use crate::js::{parse_lenient, skip_js_braces, skip_js_string, JsValue};
use crate::token::{tokenize, Span, TokenKind};
fn block_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
Regex::new(
r#"(?im)^[ \t]*(?:(config|js|pre_operations|post_operations)|input\s+(?:"([^"\n]*)"|'([^'\n]*)'))\s*\{"#,
)
.expect("valid regex")
})
}
pub fn looks_like_sqlx(text: &str) -> bool {
block_re().is_match(text) || text.contains("${")
}
pub fn decode_sqlx_bytes(bytes: &[u8]) -> String {
let body = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes);
match std::str::from_utf8(body) {
Ok(text) => text.to_string(),
Err(_) => {
let (text, _) = encoding_rs::WINDOWS_1252.decode_without_bom_handling(body);
text.into_owned()
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SqlxSectionKind {
Sql,
Config,
Js,
PreOperations,
PostOperations,
Input(String),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SqlxSection {
pub kind: SqlxSectionKind,
pub text: String,
pub span: Span,
}
impl SqlxSection {
pub fn is_block(&self) -> bool {
self.kind != SqlxSectionKind::Sql
}
pub fn body(&self) -> &str {
if !self.is_block() {
return &self.text;
}
match (self.text.find('{'), self.text.rfind('}')) {
(Some(open), Some(close)) if close > open => &self.text[open + 1..close],
_ => "",
}
}
}
fn find_balanced_brace(text: &str, opening: usize) -> Result<usize> {
let bytes = text.as_bytes();
let mut depth = 1;
let mut index = opening + 1;
let mut quote: Option<u8> = None;
let mut line_comment = false;
let mut block_comment = false;
while index < bytes.len() {
let c = bytes[index];
let next = bytes.get(index + 1).copied().unwrap_or(0);
if line_comment {
if c == b'\r' || c == b'\n' {
line_comment = false;
}
} else if block_comment {
if c == b'*' && next == b'/' {
block_comment = false;
index += 1;
}
} else if let Some(q) = quote {
if c == b'\\' {
index += 1;
} else if c == q {
if next == q {
index += 1;
} else {
quote = None;
}
}
} else if (c == b'-' && next == b'-') || (c == b'/' && next == b'/') {
line_comment = true;
index += 1;
} else if c == b'/' && next == b'*' {
block_comment = true;
index += 1;
} else if c == b'\'' || c == b'"' || c == b'`' {
quote = Some(c);
} else if c == b'{' {
depth += 1;
} else if c == b'}' {
depth -= 1;
if depth == 0 {
return Ok(index);
}
}
index += 1;
}
Err(SqlError::Sqlx("unterminated SQLX block".to_string()))
}
pub fn split_sqlx_sections(text: &str) -> Result<Vec<SqlxSection>> {
let mut pieces = Vec::new();
let mut cursor = 0;
while let Some(caps) = block_re().captures_at(text, cursor) {
let whole = caps.get(0).expect("match");
if whole.start() > cursor {
pieces.push(SqlxSection {
kind: SqlxSectionKind::Sql,
text: text[cursor..whole.start()].to_string(),
span: Span::new(cursor, whole.start()),
});
}
let kind = match caps.get(1).map(|m| m.as_str().to_ascii_lowercase()) {
Some(word) => match word.as_str() {
"config" => SqlxSectionKind::Config,
"js" => SqlxSectionKind::Js,
"pre_operations" => SqlxSectionKind::PreOperations,
_ => SqlxSectionKind::PostOperations,
},
None => SqlxSectionKind::Input(
caps.get(2)
.or(caps.get(3))
.map_or(String::new(), |m| m.as_str().to_string()),
),
};
let opening = whole.end() - 1;
let closing = find_balanced_brace(text, opening)?;
pieces.push(SqlxSection {
kind,
text: text[whole.start()..=closing].to_string(),
span: Span::new(whole.start(), closing + 1),
});
cursor = closing + 1;
}
pieces.push(SqlxSection {
kind: SqlxSectionKind::Sql,
text: text[cursor..].to_string(),
span: Span::new(cursor, text.len()),
});
Ok(pieces)
}
fn find_interpolation_end(text: &str, opening: usize) -> Result<usize> {
let bytes = text.as_bytes();
let mut depth = 1;
let mut index = opening + 2;
let mut quote: Option<u8> = None;
while index < bytes.len() {
let c = bytes[index];
let next = bytes.get(index + 1).copied().unwrap_or(0);
if let Some(q) = quote {
if c == b'\\' {
index += 1;
} else if c == q {
if next == q {
index += 1;
} else {
quote = None;
}
}
} else if c == b'\'' || c == b'"' || c == b'`' {
quote = Some(c);
} else if c == b'{' {
depth += 1;
} else if c == b'}' {
depth -= 1;
if depth == 0 {
return Ok(index);
}
}
index += 1;
}
Err(SqlError::Sqlx(
"unterminated SQLX interpolation".to_string(),
))
}
pub fn sql_comment_spans(sql: &str) -> Vec<(usize, usize)> {
let bytes = sql.as_bytes();
let size = bytes.len();
let mut spans = Vec::new();
let mut index = 0;
while index < size {
let c = bytes[index];
if sql[index..].starts_with("${") {
match find_interpolation_end(sql, index) {
Ok(end) => index = end + 1,
Err(_) => return spans,
}
} else if sql[index..].starts_with("--") {
let mut end = index;
while end < size && bytes[end] != b'\r' && bytes[end] != b'\n' {
end += 1;
}
spans.push((index, end));
index = end;
} else if sql[index..].starts_with("/*") {
let end = sql[index + 2..]
.find("*/")
.map_or(size, |e| index + 2 + e + 2);
spans.push((index, end));
index = end;
} else if c == b'\'' || c == b'"' || c == b'`' {
let triple = &sql[index..(index + 3).min(size)];
let quote: &str = if triple == "'''" || triple == "\"\"\"" {
triple
} else {
&sql[index..index + 1]
};
let quote = quote.to_string();
index += quote.len();
while index < size && !sql[index..].starts_with(quote.as_str()) {
if sql[index..].starts_with("${") {
match find_interpolation_end(sql, index) {
Ok(end) => {
index = end + 1;
continue;
}
Err(_) => return spans,
}
}
index += if bytes[index] == b'\\' { 2 } else { 1 };
}
index += quote.len();
} else {
index += 1;
}
}
spans
}
fn in_spans(spans: &[(usize, usize)], at: usize) -> bool {
spans.iter().any(|(s, e)| *s <= at && at < *e)
}
pub fn outside_sql_comments<'t>(sql: &'t str, pattern: &Regex) -> Vec<Match<'t>> {
let spans = sql_comment_spans(sql);
pattern
.find_iter(sql)
.filter(|m| !in_spans(&spans, m.start()))
.collect()
}
pub fn defuse_comment_templates(sql: &str) -> String {
if !sql.contains("${") {
return sql.to_string();
}
let mut out = String::with_capacity(sql.len());
let mut cursor = 0;
for (start, end) in sql_comment_spans(sql) {
out.push_str(&sql[cursor..start]);
out.push_str(&sql[start..end].replace("${", "$ {"));
cursor = end;
}
out.push_str(&sql[cursor..]);
out
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SqlxRestoration {
pub token: String,
pub original: String,
pub pattern: String,
pub whole: bool,
pub span: Span,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum RefFunction {
Ref,
Resolve,
SelfRef,
When,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub struct RefTarget {
pub database: Option<String>,
pub schema: Option<String>,
pub name: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RefCall {
pub function: RefFunction,
pub args: Vec<JsValue>,
pub text: String,
pub token: String,
pub nested: bool,
}
impl RefCall {
pub fn target(&self) -> Option<RefTarget> {
if !matches!(self.function, RefFunction::Ref | RefFunction::Resolve) {
return None;
}
match self.args.as_slice() {
[JsValue::String(name)] => Some(RefTarget {
name: name.clone(),
..RefTarget::default()
}),
[JsValue::String(schema), JsValue::String(name)] => Some(RefTarget {
schema: Some(schema.clone()),
name: name.clone(),
..RefTarget::default()
}),
[JsValue::String(db), JsValue::String(schema), JsValue::String(name)] => {
Some(RefTarget {
database: Some(db.clone()),
schema: Some(schema.clone()),
name: name.clone(),
})
}
[JsValue::Object(map)] => {
let name = map.get("name")?.as_str()?.to_string();
let field = |key: &str| -> Option<Option<String>> {
match map.get(key) {
None => Some(None),
Some(JsValue::String(s)) => Some(Some(s.clone())),
Some(_) => None,
}
};
Some(RefTarget {
database: field("database")?.or(field("project")?),
schema: field("schema")?.or(field("dataset")?),
name,
})
}
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MaskedSqlx {
pub original: String,
pub masked: String,
pub restorations: Vec<SqlxRestoration>,
pub refs: Vec<RefCall>,
}
impl MaskedSqlx {
pub fn opaque_tokens(&self) -> Vec<String> {
self.restorations
.iter()
.filter(|r| !is_table_reference(&r.original))
.map(|r| r.token.clone())
.collect()
}
}
fn when_connective_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
Regex::new(r#"(?i)^\s*when\s*\([^,()]*(?:\([^()]*\))?[^,()]*,\s*[`'"]\s*(AND|OR)\b"#)
.expect("valid regex")
})
}
fn when_trailing_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
let head = r"^\s*when\s*\([^,()]*(?:\([^()]*\))?[^,()]*,\s*";
let tail = r"\s*\)\s*$";
let branch = |q: &str| format!("{head}{q}[^{q}$]*?\\b(AND|OR)\\s*{q}{tail}");
Regex::new(&format!(
"(?i)(?:{})|(?:{})|(?:{})",
branch("`"),
branch("'"),
branch("\"")
))
.expect("valid regex")
})
}
fn clause_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
Regex::new(r"(?i)\b(WHERE|QUALIFY|HAVING|ORDER\s+BY)\b").expect("valid regex")
})
}
fn preceding_clause_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
Regex::new(r"(?i)\b(?:WHERE|QUALIFY|HAVING|ORDER\s+BY)\s*$").expect("valid regex")
})
}
fn preceding_condition_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"(?i)\b(?:AND|OR)\s*$").expect("valid regex"))
}
pub fn mask_sqlx(sql: &str) -> Result<MaskedSqlx> {
let comments = sql_comment_spans(sql);
let mut output = String::with_capacity(sql.len());
let mut restorations = Vec::new();
let mut refs = Vec::new();
let mut cursor = 0;
let mut ordinal = 0usize;
loop {
let mut search = cursor;
let opening = loop {
match sql[search..].find("${") {
None => break None,
Some(found) => {
let at = search + found;
if in_spans(&comments, at) {
search = at + 2;
continue;
}
break Some(at);
}
}
};
let Some(opening) = opening else {
output.push_str(&sql[cursor..]);
break;
};
output.push_str(&sql[cursor..opening]);
let closing = find_interpolation_end(sql, opening)?;
let original = &sql[opening..=closing];
let mut token = format!("__sqlx_token_{ordinal:03}__");
while sql.contains(&token) {
ordinal += 1;
token = format!("__sqlx_token_{ordinal:03}__");
}
ordinal += 1;
let prefix = output.trim_end();
let body = &original[2..original.len() - 1];
let clause = clause_re().captures(body);
let preceding_clause = preceding_clause_re().is_match(prefix);
let preceding_condition = preceding_condition_re().is_match(prefix);
let escaped = regex::escape(&token);
let mut replacement = token.clone();
let mut pattern = escaped.clone();
let mut whole = false;
let trailing = when_trailing_re().captures(body);
let connective = when_connective_re().captures(body);
if let (Some(t), true) = (&trailing, preceding_clause || preceding_condition) {
let keyword = (1..=3)
.find_map(|g| t.get(g))
.map_or("AND".to_string(), |m| m.as_str().to_ascii_uppercase());
replacement = format!("{token} {keyword}");
pattern = format!(r"(?i)\b{escaped}\s+{keyword}\b");
whole = true;
} else if let (Some(c), None, false, false) =
(&connective, &clause, preceding_clause, preceding_condition)
{
let keyword = c[1].to_ascii_uppercase();
replacement = format!("{keyword} {token}");
pattern = format!(r"(?i)\b{keyword}\s+{escaped}\b");
} else if let (Some(c), false, false) = (&clause, preceding_clause, preceding_condition) {
let keyword = c[1].to_ascii_uppercase();
if keyword.starts_with("ORDER") {
replacement = format!("ORDER BY {token}");
pattern = format!(r"(?i)\bORDER\s+BY\s+{escaped}\b");
} else {
replacement = format!("{keyword} {token}");
pattern = format!(r"(?i)\b{keyword}\s+{escaped}\b");
}
}
output.push_str(&replacement);
scan_calls(body, &token, 0, &mut refs);
restorations.push(SqlxRestoration {
token,
original: original.to_string(),
pattern,
whole,
span: Span::new(opening, closing + 1),
});
cursor = closing + 1;
}
Ok(MaskedSqlx {
original: sql.to_string(),
masked: output,
restorations,
refs,
})
}
pub fn restore_sqlx(masked: &MaskedSqlx, rewritten: &str) -> Result<String> {
restore_sqlx_interpolations(rewritten, &masked.restorations)
}
pub fn restore_sqlx_interpolations(sql: &str, restorations: &[SqlxRestoration]) -> Result<String> {
for item in restorations {
let count = sql.matches(item.token.as_str()).count();
if count != 1 {
return Err(SqlError::SqlxRestoration(format!(
"SQLX interpolation placeholder was lost or duplicated during rewriting ({count} copies found; expected one)"
)));
}
}
let mut restored = sql.to_string();
for item in restorations {
let pattern = Regex::new(&item.pattern)
.map_err(|e| SqlError::SqlxRestoration(format!("bad restoration pattern: {e}")))?;
if item.whole && pattern.find_iter(&restored).count() != 1 {
return Err(SqlError::SqlxRestoration(
"a rewrite separated a SQLX interpolation from the connective it ends with"
.to_string(),
));
}
restored = restored.replace(&format!("`{}`", item.token), &item.original);
restored = pattern
.replace_all(&restored, regex::NoExpand(&item.original))
.into_owned();
restored = restored.replace(&item.token, &item.original);
}
Ok(restored)
}
fn scan_calls(text: &str, token: &str, depth: usize, out: &mut Vec<RefCall>) {
let bytes = text.as_bytes();
let mut i = 0;
while i < bytes.len() {
let c = bytes[i];
match c {
b'\'' | b'"' => match skip_js_string(text, i) {
Some(end) => i = end,
None => return,
},
b'`' => {
let mut j = i + 1;
while j < bytes.len() && bytes[j] != b'`' {
if bytes[j] == b'\\' {
j += 2;
continue;
}
if bytes[j] == b'$' && bytes.get(j + 1) == Some(&b'{') {
let Some(end) = skip_js_braces(text, j + 1) else {
return;
};
scan_calls(&text[j + 2..end - 1], token, depth, out);
j = end;
continue;
}
j += 1;
}
i = j + 1;
}
b'/' if bytes.get(i + 1) == Some(&b'/') => {
while i < bytes.len() && bytes[i] != b'\n' {
i += 1;
}
}
b'/' if bytes.get(i + 1) == Some(&b'*') => {
i = text[i + 2..]
.find("*/")
.map_or(bytes.len(), |e| i + 2 + e + 2);
}
c if c.is_ascii_alphabetic() || c == b'_' || c == b'$' => {
let start = i;
while i < bytes.len()
&& (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_' || bytes[i] == b'$')
{
i += 1;
}
let word = &text[start..i];
let before = text[..start].trim_end();
let member_of_ctx = before.ends_with("ctx.");
let is_member = before.ends_with('.') && !member_of_ctx;
let function = match word {
"ref" => Some(RefFunction::Ref),
"resolve" => Some(RefFunction::Resolve),
"self" => Some(RefFunction::SelfRef),
"when" => Some(RefFunction::When),
_ => None,
};
let after = text[i..].trim_start();
if let (Some(function), false, true) = (function, is_member, after.starts_with('('))
{
let open = i + (text[i..].len() - after.len());
if let Some(close) = skip_js_braces(text, open) {
let args_text = &text[open + 1..close - 1];
out.push(RefCall {
function,
args: parse_arguments(args_text),
text: text[start..close].to_string(),
token: token.to_string(),
nested: depth > 0,
});
scan_calls(args_text, token, depth + 1, out);
i = close;
}
}
}
_ => i += 1,
}
}
}
fn parse_arguments(text: &str) -> Vec<JsValue> {
let mut args = Vec::new();
let mut pos = 0;
loop {
let rest = &text[pos..];
if rest.trim().is_empty() {
break;
}
let Some((value, end)) = parse_lenient(text, pos) else {
args.push(JsValue::Expression(rest.trim().to_string()));
break;
};
args.push(value);
let after = &text[end..];
let trimmed = after.trim_start();
if let Some(next) = trimmed.strip_prefix(',') {
pos = text.len() - next.len();
} else {
break;
}
}
args
}
fn quoted() -> &'static str {
r#"(?:"[^"\\]*"|'[^'\\]*'|`[^`\\]*`)"#
}
fn table_reference_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
let q = quoted();
Regex::new(&format!(
r"^\$\{{\s*(?:(?:ref|resolve)\s*\(\s*{q}(?:\s*,\s*{q})?\s*\)|self\s*\(\s*\))\s*\}}$"
))
.expect("valid regex")
})
}
pub fn is_table_reference(original: &str) -> bool {
table_reference_re().is_match(original)
}
pub fn is_relation_reference(interpolation: &str) -> bool {
static SELF_RE: OnceLock<Regex> = OnceLock::new();
static CALL_RE: OnceLock<Regex> = OnceLock::new();
static CLOSE_RE: OnceLock<Regex> = OnceLock::new();
let self_re =
SELF_RE.get_or_init(|| Regex::new(r"^\$\{\s*self\(\s*\)\s*\}$").expect("valid regex"));
let call_re =
CALL_RE.get_or_init(|| Regex::new(r"^\$\{\s*(?:ref|resolve)\s*\(").expect("valid regex"));
let close_re = CLOSE_RE.get_or_init(|| Regex::new(r"^\s*\}$").expect("valid regex"));
if self_re.is_match(interpolation) {
return true;
}
let Some(call) = call_re.find(interpolation) else {
return false;
};
let mut depth = 1;
let mut quote: Option<char> = None;
for (index, c) in interpolation[call.end()..].char_indices() {
let at = call.end() + index;
if "`/\\".contains(c) || (quote.is_some() && c == '\n') {
return false;
}
if let Some(q) = quote {
if c == q {
quote = None;
}
} else if c == '\'' || c == '"' {
quote = Some(c);
} else if "([{".contains(c) {
depth += 1;
} else if ")]}".contains(c) {
depth -= 1;
if depth == 0 {
return c == ')' && close_re.is_match(&interpolation[at + 1..]);
}
}
}
false
}
pub fn content_sentinel(original: &str) -> String {
let digest = Sha256::digest(original.as_bytes());
format!("__sqlx_{}__", &hex::encode(digest)[..16])
}
pub fn mask_sqlx_by_content(sql: &str) -> Result<String> {
let masked = mask_sqlx(sql)?;
let mut text = masked.masked.clone();
for item in &masked.restorations {
text = text.replace(&item.token, &content_sentinel(&item.original));
}
Ok(text)
}
pub fn dynamic_sentinels(sql: &str) -> Result<Vec<String>> {
let masked = mask_sqlx(sql)?;
let mut out: Vec<String> = masked
.restorations
.iter()
.filter(|r| !is_relation_reference(&r.original))
.map(|r| content_sentinel(&r.original))
.collect();
out.sort();
out.dedup();
Ok(out)
}
pub const LOADER_TOKEN_REASON: &str = "unsupported: it holds a Dataform expression the loader masked by position (__sqlx_token_N__), which can expand to any SQL and stands for a different expression in each model; compile the SQLX to prove it";
pub const STRING_REASON: &str = "unsupported: a string literal holds a masked Dataform expression, so its value is unknown; compile the SQLX to prove it";
pub fn masked_template_problem(sqls: &[&str]) -> Option<&'static str> {
static LOADER: OnceLock<Regex> = OnceLock::new();
let loader = LOADER.get_or_init(|| Regex::new(r"__sqlx_token_\d+__").expect("valid regex"));
for sql in sqls {
if !sql.contains("__sqlx_") {
continue;
}
if loader.is_match(sql) {
return Some(LOADER_TOKEN_REASON);
}
match tokenize(sql) {
Ok(tokens) => {
if tokens.iter().any(|t| {
matches!(t.kind, TokenKind::String { .. } | TokenKind::Bytes { .. })
&& t.text.contains("__sqlx_")
}) {
return Some(STRING_REASON);
}
}
Err(_) => return Some(STRING_REASON),
}
}
None
}
pub fn with_preserved_whitespace(original: &str, transformed: &str) -> String {
if transformed.is_empty() {
return original.to_string();
}
let leading = &original[..original.len() - original.trim_start().len()];
let trailing = &original[original.trim_end().len()..];
format!("{leading}{}{trailing}", transformed.trim())
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum SqlxDependency {
Name(String),
Target(RefTarget),
Computed(String),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct SqlxColumn {
pub description: Option<String>,
pub columns: IndexMap<String, SqlxColumn>,
pub policy_tags: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct SqlxBigQuery {
pub partition_by: Option<String>,
pub cluster_by: Vec<String>,
pub labels: IndexMap<String, String>,
pub require_partition_filter: Option<bool>,
pub partition_expiration_days: Option<String>,
pub update_partition_filter: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct SqlxAssertions {
pub unique_key: Vec<String>,
pub unique_keys: Vec<Vec<String>>,
pub non_null: Vec<String>,
pub row_conditions: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct SqlxConfig {
pub action_type: Option<String>,
pub schema: Option<String>,
pub database: Option<String>,
pub name: Option<String>,
pub tags: Vec<String>,
pub disabled: Option<bool>,
pub protected: Option<bool>,
pub has_output: Option<bool>,
pub description: Option<String>,
pub columns: IndexMap<String, SqlxColumn>,
pub dependencies: Vec<SqlxDependency>,
pub bigquery: SqlxBigQuery,
pub assertions: SqlxAssertions,
pub unique_key: Vec<String>,
pub computed: Vec<String>,
pub problems: Vec<String>,
pub raw: IndexMap<String, JsValue>,
}
impl SqlxConfig {
pub fn effective_type(&self) -> &str {
self.action_type.as_deref().unwrap_or("table")
}
}
const COMMON_CONFIG_KEYS: &[&str] = &[
"additionalOptions",
"assertions",
"bigquery",
"columns",
"database",
"dataset",
"dependOnDependencyAssertions",
"dependencies",
"dependencyTargets",
"description",
"disabled",
"filename",
"hermetic",
"iceberg",
"incrementalPredicates",
"labels",
"metadata",
"name",
"preserveGovernanceControls",
"project",
"protected",
"requirePartitionFilter",
"schema",
"tags",
"type",
];
fn type_keys(action_type: &str) -> Option<&'static [&'static str]> {
Some(match action_type {
"table" | "test" => &[
"clusterBy",
"fileName",
"partitionBy",
"partitionExpirationDays",
"reservation",
],
"view" => &[
"clusterBy",
"fileName",
"materialized",
"partitionBy",
"reservation",
],
"incremental" => &[
"clusterBy",
"fileName",
"incrementalStrategy",
"onSchemaChange",
"partitionBy",
"partitionExpirationDays",
"reservation",
"uniqueKey",
"updatePartitionFilter",
],
"assertion" => &["fileName", "reservation"],
"operations" => &["fileName", "hasOutput", "reservation"],
"declaration" => &[],
_ => return None,
})
}
fn unique(items: Vec<String>) -> Vec<String> {
let mut seen = std::collections::HashSet::new();
items
.into_iter()
.filter(|i| seen.insert(i.clone()))
.collect()
}
fn literal_string(
map: &IndexMap<String, JsValue>,
key: &str,
computed: &mut Vec<String>,
) -> Option<String> {
match map.get(key)? {
JsValue::String(s) => Some(s.clone()),
_ => {
computed.push(key.to_string());
None
}
}
}
fn literal_bool(
map: &IndexMap<String, JsValue>,
key: &str,
computed: &mut Vec<String>,
) -> Option<bool> {
match map.get(key)? {
JsValue::Bool(b) => Some(*b),
_ => {
computed.push(key.to_string());
None
}
}
}
fn literal_list(
map: &IndexMap<String, JsValue>,
key: &str,
path: &str,
computed: &mut Vec<String>,
) -> Vec<String> {
match map.get(key) {
None => Vec::new(),
Some(value) => value.string_list().unwrap_or_else(|| {
computed.push(format!("{path}{key}"));
Vec::new()
}),
}
}
fn read_columns(value: &JsValue) -> IndexMap<String, SqlxColumn> {
let mut out = IndexMap::new();
if let Some(map) = value.as_object() {
for (name, doc) in map {
let column = match doc {
JsValue::String(text) => SqlxColumn {
description: Some(text.clone()),
..SqlxColumn::default()
},
JsValue::Object(fields) => SqlxColumn {
description: fields
.get("description")
.and_then(|d| d.as_str())
.map(str::to_string),
columns: fields.get("columns").map(read_columns).unwrap_or_default(),
policy_tags: fields
.get("bigqueryPolicyTags")
.and_then(JsValue::string_list)
.unwrap_or_default(),
},
_ => SqlxColumn::default(),
};
out.insert(name.clone(), column);
}
}
out
}
fn read_dependency(value: &JsValue) -> SqlxDependency {
match value {
JsValue::String(name) => SqlxDependency::Name(name.clone()),
JsValue::Object(map) => {
let get = |k: &str| map.get(k).and_then(|v| v.as_str()).map(str::to_string);
match get("name") {
Some(name) => SqlxDependency::Target(RefTarget {
database: get("database").or_else(|| get("project")),
schema: get("schema").or_else(|| get("dataset")),
name,
}),
None => SqlxDependency::Computed(format!("{value:?}")),
}
}
JsValue::Expression(text) => SqlxDependency::Computed(text.clone()),
other => SqlxDependency::Computed(format!("{other:?}")),
}
}
fn unique_keys(value: &JsValue) -> Option<Vec<Vec<String>>> {
value
.as_array()?
.iter()
.map(|entry| match entry {
JsValue::Object(map) => map.get("uniqueKey").and_then(JsValue::string_list),
other => other.string_list(),
})
.collect()
}
pub fn parse_sqlx_config(config_block: &str) -> Result<SqlxConfig> {
let text = config_block.trim();
if text.is_empty() {
return Ok(SqlxConfig::default());
}
let start = if text
.get(..6)
.is_some_and(|head| head.eq_ignore_ascii_case("config"))
{
6
} else {
0
};
let rest = text[start..].trim_start();
if !rest.starts_with('{') {
return Err(SqlError::Sqlx(
"a config block must be an object in braces".to_string(),
));
}
let offset = text.len() - rest.len();
let (value, end) = parse_lenient(text, offset).ok_or_else(|| {
SqlError::Sqlx("the config block is not a readable JavaScript object".to_string())
})?;
let trailing = crate::js::strip_comments(&text[end..]);
if !trailing.trim().is_empty() {
return Err(SqlError::Sqlx(
"unexpected text after the config object".to_string(),
));
}
let JsValue::Object(map) = value else {
return Err(SqlError::Sqlx(
"a config block must be an object in braces".to_string(),
));
};
let mut config = SqlxConfig::default();
let mut computed = Vec::new();
config.action_type = literal_string(&map, "type", &mut computed);
config.schema = literal_string(&map, "schema", &mut computed)
.or_else(|| literal_string(&map, "dataset", &mut computed));
config.database = literal_string(&map, "database", &mut computed)
.or_else(|| literal_string(&map, "project", &mut computed));
config.name = literal_string(&map, "name", &mut computed);
config.tags = unique(literal_list(&map, "tags", "", &mut computed));
config.disabled = literal_bool(&map, "disabled", &mut computed);
config.protected = literal_bool(&map, "protected", &mut computed);
config.has_output = literal_bool(&map, "hasOutput", &mut computed);
config.description = literal_string(&map, "description", &mut computed);
if let Some(columns) = map.get("columns") {
if columns.as_object().is_none() {
computed.push("columns".to_string());
}
config.columns = read_columns(columns);
}
match map.get("dependencies") {
Some(JsValue::Array(items)) => {
config.dependencies = items.iter().map(read_dependency).collect()
}
Some(single @ (JsValue::String(_) | JsValue::Object(_))) => {
config.dependencies = vec![read_dependency(single)]
}
Some(_) => computed.push("dependencies".to_string()),
None => {}
}
let bq_map = match map.get("bigquery") {
Some(JsValue::Object(m)) => Some(m.clone()),
Some(_) => {
computed.push("bigquery".to_string());
None
}
None => None,
};
let empty = IndexMap::new();
let bq = bq_map.as_ref().unwrap_or(&empty);
let mut bigquery = SqlxBigQuery {
partition_by: literal_string(bq, "partitionBy", &mut computed),
cluster_by: literal_list(bq, "clusterBy", "bigquery.", &mut computed),
require_partition_filter: literal_bool(bq, "requirePartitionFilter", &mut computed),
update_partition_filter: literal_string(bq, "updatePartitionFilter", &mut computed),
partition_expiration_days: bq.get("partitionExpirationDays").map(|v| match v {
JsValue::Number(n) => n.clone(),
other => format!("{other:?}"),
}),
labels: IndexMap::new(),
};
for (key, source) in [("labels", bq.get("labels")), ("labels", map.get("labels"))] {
if let Some(JsValue::Object(labels)) = source {
for (k, v) in labels {
match v.as_str() {
Some(s) => {
bigquery.labels.insert(k.clone(), s.to_string());
}
None => computed.push(format!("{key}.{k}")),
}
}
}
}
if bigquery.partition_by.is_none() {
bigquery.partition_by = literal_string(&map, "partitionBy", &mut computed);
}
if bigquery.cluster_by.is_empty() {
bigquery.cluster_by = literal_list(&map, "clusterBy", "", &mut computed);
}
if bigquery.update_partition_filter.is_none() {
bigquery.update_partition_filter =
literal_string(&map, "updatePartitionFilter", &mut computed);
}
if bigquery.require_partition_filter.is_none() {
bigquery.require_partition_filter =
literal_bool(&map, "requirePartitionFilter", &mut computed);
}
config.bigquery = bigquery;
match map.get("assertions") {
Some(JsValue::Object(a)) => {
config.assertions.unique_key =
literal_list(a, "uniqueKey", "assertions.", &mut computed);
if let Some(keys) = a.get("uniqueKeys") {
match unique_keys(keys) {
Some(keys) => config.assertions.unique_keys = keys,
None => computed.push("assertions.uniqueKeys".to_string()),
}
}
config.assertions.non_null = literal_list(a, "nonNull", "assertions.", &mut computed);
config.assertions.row_conditions =
literal_list(a, "rowConditions", "assertions.", &mut computed);
}
Some(_) => computed.push("assertions".to_string()),
None => {}
}
config.unique_key = literal_list(&map, "uniqueKey", "", &mut computed);
if map.contains_key("type") && config.action_type.is_some() {
let declared = config.action_type.as_deref().unwrap_or("table");
if type_keys(declared).is_none() {
config.problems.push(format!(
"type '{declared}' is not an action type Dataform recognizes"
));
}
}
let type_is_known = !computed.iter().any(|c| c == "type");
if type_is_known && config.problems.is_empty() {
let declared = config.effective_type().to_string();
if let Some(extra) = type_keys(&declared) {
for key in map.keys() {
if !COMMON_CONFIG_KEYS.contains(&key.as_str()) && !extra.contains(&key.as_str()) {
config.problems.push(format!(
"config key '{key}' is not accepted for type '{declared}'"
));
}
}
}
}
if type_is_known && config.effective_type() == "declaration" {
if let Some(JsValue::Object(block)) = map.get("assertions") {
if !block.is_empty() {
config.problems.push(
"config key 'assertions' must be empty ({}) for type 'declaration'".to_string(),
);
}
}
}
config.computed = unique(computed);
config.raw = map;
Ok(config)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detects_sqlx() {
assert!(looks_like_sqlx("config { type: \"table\" }\nSELECT 1"));
assert!(looks_like_sqlx("SELECT * FROM ${ref(\"t\")}"));
assert!(looks_like_sqlx(" input \"a\" {\n SELECT 1 }"));
assert!(!looks_like_sqlx("SELECT 1 -- config"));
assert!(!looks_like_sqlx("SELECT '{config}'"));
}
#[test]
fn decodes_bytes() {
assert_eq!(decode_sqlx_bytes(b"\xEF\xBB\xBFconfig {}"), "config {}");
assert_eq!(
decode_sqlx_bytes(b"caf\xE9 \x93q\x94"),
"caf\u{e9} \u{201c}q\u{201d}"
);
assert_eq!(decode_sqlx_bytes("é".as_bytes()), "é");
}
#[test]
fn splits_sections_with_js_comments() {
let text = "config {\n type: \"table\", // don't { break\n tags: ['a'] /* } */\n}\njs {\n const x = '}';\n}\nSELECT ${ref(\"t\")} -- it's\npre_operations { SET x = 1 }\ninput \"src\" { SELECT 1 }\n";
let sections = split_sqlx_sections(text).unwrap();
let kinds: Vec<_> = sections.iter().map(|s| s.kind.clone()).collect();
assert_eq!(
kinds,
vec![
SqlxSectionKind::Config,
SqlxSectionKind::Sql,
SqlxSectionKind::Js,
SqlxSectionKind::Sql,
SqlxSectionKind::PreOperations,
SqlxSectionKind::Sql,
SqlxSectionKind::Input("src".into()),
SqlxSectionKind::Sql,
]
);
let joined: String = sections.iter().map(|s| s.text.as_str()).collect();
assert_eq!(joined, text);
assert!(sections[0].body().contains("tags"));
assert!(split_sqlx_sections("config { type: 'x'").is_err());
}
#[test]
fn comment_spans_skip_strings_and_interpolations() {
let sql = "SELECT '--x', ${ref('a--b')} -- c\n/* d */ # e\n";
let spans = sql_comment_spans(sql);
assert_eq!(spans.len(), 2);
assert_eq!(&sql[spans[0].0..spans[0].1], "-- c");
assert_eq!(&sql[spans[1].0..spans[1].1], "/* d */");
assert_eq!(
defuse_comment_templates("-- ${x}\nSELECT ${y}"),
"-- $ {x}\nSELECT ${y}"
);
}
#[test]
fn masks_and_restores() {
let sql = "SELECT * FROM ${ref(\"ds\", \"t\")} AS t -- ${ref(\"ignored\")}\n# ${ref(\"evaluated\")}\nWHERE ${when(incremental(), \"ts > 1 AND\")} x = 1";
let masked = mask_sqlx(sql).unwrap();
assert_eq!(masked.restorations.len(), 3);
assert!(masked.masked.contains("FROM __sqlx_token_000__ AS t"));
assert!(masked.masked.contains("-- ${ref(\"ignored\")}"));
assert!(masked.masked.contains("WHERE __sqlx_token_002__ AND x = 1"));
let targets: Vec<_> = masked.refs.iter().filter_map(RefCall::target).collect();
assert_eq!(targets.len(), 2);
assert_eq!(targets[0].schema.as_deref(), Some("ds"));
assert_eq!(targets[1].name, "evaluated");
assert!(masked.refs.iter().any(|r| r.function == RefFunction::When));
assert_eq!(restore_sqlx(&masked, &masked.masked).unwrap(), sql);
let rewritten = masked.masked.replace("AS t", "AS u");
assert!(restore_sqlx(&masked, &rewritten)
.unwrap()
.contains("${ref(\"ds\", \"t\")} AS u"));
let lost = masked.masked.replace("__sqlx_token_000__", "x");
assert!(matches!(
restore_sqlx(&masked, &lost),
Err(SqlError::SqlxRestoration(_))
));
let dup = format!("{} {}", masked.masked, "__sqlx_token_001__");
assert!(restore_sqlx(&masked, &dup).is_err());
let separated = masked
.masked
.replace("__sqlx_token_002__ AND", "__sqlx_token_002__ OR");
assert!(restore_sqlx(&masked, &separated).is_err());
}
#[test]
fn masks_clause_interpolations() {
let m = mask_sqlx(
"SELECT * FROM t ${when(incremental(), `WHERE ts > (SELECT MAX(ts) FROM ${self()})`)}",
)
.unwrap();
assert!(
m.masked.ends_with("WHERE __sqlx_token_000__"),
"{}",
m.masked
);
assert!(m
.refs
.iter()
.any(|r| r.function == RefFunction::SelfRef && r.nested));
assert_eq!(restore_sqlx(&m, &m.masked).unwrap(), m.original);
let m =
mask_sqlx("SELECT * FROM t WHERE a > 0 ${when(incremental(), \"AND b > 1\")}").unwrap();
assert!(
m.masked.contains("a > 0 AND __sqlx_token_000__"),
"{}",
m.masked
);
let restored = restore_sqlx(&m, &m.masked.replace("a > 0 AND", "a > 0\n AND")).unwrap();
assert!(restored.contains("${when("));
let m = mask_sqlx("SELECT 1 ${\"ORDER BY x\"}").unwrap();
assert!(m.masked.ends_with("ORDER BY __sqlx_token_000__"));
}
#[test]
fn sentinels_avoid_existing_text_and_backticks_restore() {
let m = mask_sqlx("SELECT '__sqlx_token_000__', ${x}").unwrap();
assert_eq!(m.restorations[0].token, "__sqlx_token_001__");
let m = mask_sqlx("SELECT * FROM ${ref('t')}").unwrap();
let quoted = m
.masked
.replace("__sqlx_token_000__", "`__sqlx_token_000__`");
assert_eq!(restore_sqlx(&m, "ed).unwrap(), m.original);
let m = mask_sqlx("SELECT REGEXP_EXTRACT(a, r'\\d$1') FROM ${ref('t')}").unwrap();
assert_eq!(restore_sqlx(&m, &m.masked).unwrap(), m.original);
}
#[test]
fn relation_references() {
assert!(is_table_reference("${ref(\"t\")}"));
assert!(is_table_reference("${ ref('d', 't') }"));
assert!(is_table_reference("${self()}"));
assert!(!is_table_reference("${ref({schema: 's', name: 't'})}"));
assert!(is_relation_reference(
"${ref({schema: vars.S, name: \"t\"})}"
));
assert!(is_relation_reference("${resolve(\"t\")}"));
assert!(!is_relation_reference("${ref(\"t\") + \" OR x\"}"));
assert!(!is_relation_reference("${ref(a /* ( */) + x)}"));
assert!(!is_relation_reference("${when(incremental(), \"x\")}"));
let m = mask_sqlx("SELECT * FROM ${ref('t')} WHERE ${\"x OR y\"}").unwrap();
assert_eq!(m.opaque_tokens(), vec!["__sqlx_token_001__".to_string()]);
}
#[test]
fn content_masking_and_problems() {
let a = mask_sqlx_by_content("SELECT * FROM ${ref('t')}").unwrap();
let b = mask_sqlx_by_content("SELECT x FROM ${ref('t')} AS y").unwrap();
let sentinel = content_sentinel("${ref('t')}");
assert!(a.contains(&sentinel) && b.contains(&sentinel));
assert_eq!(sentinel.len(), "__sqlx_".len() + 16 + 2);
assert_eq!(
dynamic_sentinels("SELECT ${x}, ${ref('t')}").unwrap(),
vec![content_sentinel("${x}")]
);
assert_eq!(
masked_template_problem(&["SELECT __sqlx_token_000__"]),
Some(LOADER_TOKEN_REASON)
);
assert_eq!(
masked_template_problem(&[&format!("SELECT '{sentinel}'")]),
Some(STRING_REASON)
);
assert_eq!(
masked_template_problem(&[&format!("SELECT * FROM {sentinel}")]),
None
);
assert_eq!(with_preserved_whitespace(" a \n", "b"), " b \n");
assert_eq!(with_preserved_whitespace(" a \n", ""), " a \n");
}
#[test]
fn parses_config_blocks() {
let config = parse_sqlx_config(
r#"config {
type: 'incremental', // it's incremental {
schema: "analytics",
name: `daily`,
tags: ["a", 'b',],
disabled: false,
description: "Daily rollup",
columns: { id: "the key", payload: { description: "nested", columns: { x: "inner" }, bigqueryPolicyTags: ["p"] } },
dependencies: ["dep_one", {name: "dep_two", schema: "raw"}],
uniqueKey: ["id"],
bigquery: { partitionBy: "DATE(ts)", clusterBy: ["id", "kind"], labels: { team: "data" } },
assertions: { uniqueKey: ["id"], uniqueKeys: [["a", "b"], {uniqueKey: ["c"]}], nonNull: "id", rowConditions: ["x > 0"] },
}"#,
)
.unwrap();
assert_eq!(config.action_type.as_deref(), Some("incremental"));
assert_eq!(config.schema.as_deref(), Some("analytics"));
assert_eq!(config.name.as_deref(), Some("daily"));
assert_eq!(config.tags, vec!["a", "b"]);
assert_eq!(config.disabled, Some(false));
assert_eq!(
config.columns["payload"].columns["x"]
.description
.as_deref(),
Some("inner")
);
assert_eq!(config.columns["payload"].policy_tags, vec!["p"]);
assert_eq!(config.dependencies.len(), 2);
assert!(
matches!(&config.dependencies[1], SqlxDependency::Target(t) if t.schema.as_deref() == Some("raw"))
);
assert_eq!(config.bigquery.partition_by.as_deref(), Some("DATE(ts)"));
assert_eq!(config.bigquery.cluster_by, vec!["id", "kind"]);
assert_eq!(config.bigquery.labels["team"], "data");
assert_eq!(
config.assertions.unique_keys,
vec![
vec!["a".to_string(), "b".to_string()],
vec!["c".to_string()]
]
);
assert_eq!(config.assertions.non_null, vec!["id"]);
assert_eq!(config.assertions.row_conditions, vec!["x > 0"]);
assert_eq!(config.unique_key, vec!["id"]);
assert!(config.problems.is_empty(), "{:?}", config.problems);
assert!(config.computed.is_empty(), "{:?}", config.computed);
}
#[test]
fn tolerates_empty_and_computed_configs() {
assert_eq!(parse_sqlx_config("").unwrap(), SqlxConfig::default());
let c = parse_sqlx_config("config {}").unwrap();
assert_eq!(c.effective_type(), "table");
let c = parse_sqlx_config("config { tags: [] }").unwrap();
assert!(c.tags.is_empty());
let c = parse_sqlx_config(
"{ schema: dataform.projectConfig.vars.s, type: \"view\", name: \"a\" + suffix }",
)
.unwrap();
assert_eq!(c.schema, None);
assert!(c.computed.contains(&"schema".to_string()));
assert!(c.computed.contains(&"name".to_string()));
let c = parse_sqlx_config("config { type: \"table\", uniqueKey: [\"id\"] }").unwrap();
assert_eq!(
c.problems,
vec!["config key 'uniqueKey' is not accepted for type 'table'"]
);
let c = parse_sqlx_config("config { type: \"tabel\" }").unwrap();
assert_eq!(c.problems.len(), 1);
assert!(parse_sqlx_config("config { type: ").is_err());
assert!(parse_sqlx_config("SELECT 1").is_err());
}
}