From f1957e35d1720bc91095f2417f9b2b735ececa33 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Tue, 24 Nov 2026 20:56:46 +0800 Subject: [PATCH 01/12] feat(metrics): add SQL dialect config and Hazards Metric Add sql.dialects and hazards.disabled_rules configuration with JSON Schema validation, Hazards Budgets and Regression limits across all Source sets, optional sql.dialects starter hint, language-agnostic Hazards Metric with per-package breakdowns and stable FindingIds, and reserve the hazards key for external Metric plugins. --- crates/config/src/codeint_json.rs | 119 ++++- crates/config/src/codeint_json/starter.rs | 14 +- .../config/src/codeint_json/starter/tests.rs | 19 + crates/config/src/config_error.rs | 22 +- crates/config/src/hazards.rs | 55 ++ crates/config/src/lib.rs | 10 +- crates/config/src/regression_limits.rs | 1 + crates/config/src/sql.rs | 218 ++++++++ crates/config/tests/sql_hazards.rs | 499 ++++++++++++++++++ crates/metrics/src/hazards.rs | 156 ++++++ crates/metrics/src/hazards/tests.rs | 242 +++++++++ crates/metrics/src/lib.rs | 2 + crates/plugin-host/src/wasm_metric.rs | 3 +- crates/plugin-host/src/wasm_metric/tests.rs | 1 + schema/codeint.schema.json | 86 +++ 15 files changed, 1410 insertions(+), 37 deletions(-) create mode 100644 crates/config/src/hazards.rs create mode 100644 crates/config/src/sql.rs create mode 100644 crates/config/tests/sql_hazards.rs create mode 100644 crates/metrics/src/hazards.rs create mode 100644 crates/metrics/src/hazards/tests.rs diff --git a/crates/config/src/codeint_json.rs b/crates/config/src/codeint_json.rs index 63912062..7979f2a0 100644 --- a/crates/config/src/codeint_json.rs +++ b/crates/config/src/codeint_json.rs @@ -10,11 +10,13 @@ use crate::config_error::{ JsonType, JsoncError, KeyPath, KeySegment, compile_glob, glob_set, }; use crate::dependencies::{DependenciesConfig, DependenciesFile}; +use crate::hazards::{HazardsConfig, HazardsConfigFile}; use crate::regression_limits::{RegressionLimitSetting, ResolvedRegressionLimit}; use crate::resolved::{ BudgetOverride, ConfigOverrides, ConfigProvenance, ResolvedConfiguration, ResolvedSetting, SourceSetOverride, resolve_with_provenance, }; +use crate::sql::{SqlConfig, SqlConfigFile}; use globset::GlobSet; use jsonc_parser::errors::ParseError; use jsonc_parser::{ @@ -31,6 +33,7 @@ pub const DEPENDENCY_METRIC_KEYS: [&str; 3] = [ ]; pub const TEST_GAP_METRIC_KEY: &str = "test_gap"; +pub const HAZARDS_METRIC_KEY: &str = "hazards"; mod shape; mod starter; @@ -116,6 +119,8 @@ pub struct Configuration { pub duplication: DuplicationConfig, pub entry_points: EntryPoints, pub coverage_reports: Vec, + pub sql: SqlConfig, + pub hazards: HazardsConfig, config_file: ConfigFileKind, effective: ConfigurationFile, } @@ -320,10 +325,17 @@ fn allowed_budget_metric_keys(source_set: SourceSet, external_metric_keys: &[&st allowed } +const EXTRA_BUILT_IN_METRIC_KEYS: [&str; 4] = [ + "cognitive_complexity", + "boundaries", + "orphan_files", + HAZARDS_METRIC_KEY, +]; + fn allowed_metric_keys(external_metric_keys: &[&str]) -> Vec { Metric::BUILT_IN_KEYS .iter() - .chain(["cognitive_complexity", "boundaries", "orphan_files"].iter()) + .chain(EXTRA_BUILT_IN_METRIC_KEYS.iter()) .chain(external_metric_keys.iter()) .map(|key| (*key).to_owned()) .collect() @@ -331,9 +343,7 @@ fn allowed_metric_keys(external_metric_keys: &[&str]) -> Vec { fn is_known_metric(key: &str, external_metric_keys: &[&str]) -> bool { Metric::BUILT_IN_KEYS.contains(&key) - || key == "cognitive_complexity" - || key == "boundaries" - || key == "orphan_files" + || EXTRA_BUILT_IN_METRIC_KEYS.contains(&key) || external_metric_keys.contains(&key) } @@ -566,6 +576,14 @@ struct ConfigurationFile { description = "Paths relative to the repository root of LCOV or Cobertura XML Coverage reports used to measure Test gap." )] coverage_reports: Vec, + #[serde(default, skip_serializing_if = "SqlConfigFile::is_unset")] + #[schemars(description = "SQL settings, including Dialect mappings for folders or files.")] + sql: SqlConfigFile, + #[serde(default, skip_serializing_if = "crate::hazards::is_hazards_unset")] + #[schemars( + description = "Hazards Metric settings, including Hazard line rules turned off across the repository." + )] + hazards: HazardsConfigFile, } #[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)] @@ -677,6 +695,9 @@ struct RegressionLimitsFile { #[schemars(description = "The Regression limit of Orphan files in every Source set.")] orphan_files: RegressionLimitSetting, #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")] + #[schemars(description = "The Regression limit of Hazards in every Source set.")] + hazards: RegressionLimitSetting, + #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")] #[schemars(description = "The Regression limit of unused declared dependencies.")] unused_dependencies: RegressionLimitSetting, #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")] @@ -724,6 +745,9 @@ struct MetricRegressionLimits { #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")] #[schemars(description = "The Regression limit of Orphan files in this Source set.")] orphan_files: RegressionLimitSetting, + #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")] + #[schemars(description = "The Regression limit of Hazards in this Source set.")] + hazards: RegressionLimitSetting, #[serde(flatten, default, skip_serializing_if = "BTreeMap::is_empty")] external: BTreeMap, } @@ -738,6 +762,7 @@ impl MetricRegressionLimits { &self.import_cycles, &self.boundaries, &self.orphan_files, + &self.hazards, ] .into_iter() .chain(self.external.values()) @@ -753,6 +778,7 @@ impl MetricRegressionLimits { import_cycles, boundaries, orphan_files, + hazards, external, } = self; built_in_metric_pairs([ @@ -763,13 +789,14 @@ impl MetricRegressionLimits { import_cycles, boundaries, orphan_files, + hazards, ]) .chain(external) .filter(|(_, setting)| !setting.is_unset()) } } -fn built_in_metric_pairs(values: [T; 7]) -> impl Iterator { +fn built_in_metric_pairs(values: [T; 8]) -> impl Iterator { [ Metric::Erosion.key(), "cognitive_complexity", @@ -778,6 +805,7 @@ fn built_in_metric_pairs(values: [T; 7]) -> impl Iterator Metric::ImportCycles.key(), "boundaries", "orphan_files", + HAZARDS_METRIC_KEY, ] .into_iter() .zip(values) @@ -896,6 +924,13 @@ struct SharedMetricBudgets { description = "The highest Orphan files ratio, from 0 to 1." )] orphan_files: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schemars( + with = "f64", + range(min = 0, max = 1), + description = "The highest Hazards ratio, from 0 to 1." + )] + hazards: Option, } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)] @@ -1367,6 +1402,8 @@ fn parse_value_with_overrides( &effective.coverage_reports, &mut settings, )?; + let (sql, hazards) = + parse_sql_and_hazards(raw.as_ref(), file.sql, file.hazards, &mut settings)?; let configuration = Configuration { config_file: config_file_kind, effective, @@ -1381,6 +1418,8 @@ fn parse_value_with_overrides( duplication: features.duplication, entry_points: features.entry_points, coverage_reports: features.coverage_reports, + sql, + hazards, }; Ok(ResolvedConfiguration { config_file, @@ -1390,6 +1429,36 @@ fn parse_value_with_overrides( }) } +fn parse_sql_and_hazards( + raw: Option<&Value>, + sql_file: SqlConfigFile, + hazards_file: HazardsConfigFile, + settings: &mut Vec, +) -> Result<(SqlConfig, HazardsConfig), ConfigurationFileError> { + let dialects_json = serde_json::to_value(&sql_file.dialects).unwrap_or_else(|_| json!([])); + let sql = SqlConfig::from_file(sql_file)?; + let sql_source = if has_json_path(raw, &["sql", "dialects"]) { + ConfigProvenance::File + } else { + ConfigProvenance::Default + }; + push_setting(settings, "sql.dialects", dialects_json, sql_source); + + let hazards = HazardsConfig::from_file(hazards_file)?; + let hazards_source = if has_json_path(raw, &["hazards", "disabled_rules"]) { + ConfigProvenance::File + } else { + ConfigProvenance::Default + }; + push_setting( + settings, + "hazards.disabled_rules", + json!(hazards.disabled_rules), + hazards_source, + ); + Ok((sql, hazards)) +} + fn append_dependencies_settings( raw: Option<&Value>, dependencies: &DependenciesConfig, @@ -1687,11 +1756,7 @@ fn append_regression_limit_settings( limits: &RegressionLimits, settings: &mut Vec, ) { - let mut metric_keys: Vec = Metric::BUILT_IN_KEYS - .iter() - .chain(["cognitive_complexity", "boundaries", "orphan_files"].iter()) - .map(|key| (*key).to_owned()) - .collect(); + let mut metric_keys = allowed_metric_keys(&[]); metric_keys.extend(limits.extra_metric_keys()); for source_set in ORDERED_SOURCE_SETS { for metric_key in &metric_keys { @@ -1881,31 +1946,25 @@ impl SharedMetricBudgets { "import_cycles" => self.import_cycles = Some(budget), "boundaries" => self.boundaries = Some(budget), "orphan_files" => self.orphan_files = Some(budget), + "hazards" => self.hazards = Some(budget), _ => return false, } true } fn into_pairs(self) -> impl Iterator { - let SharedMetricBudgets { - erosion, - cognitive_complexity, - duplication, - verbosity, - import_cycles, - boundaries, - orphan_files, - } = self; - built_in_metric_pairs([ - erosion, - cognitive_complexity, - duplication, - verbosity, - import_cycles, - boundaries, - orphan_files, - ]) - .filter_map(|(metric, ratio)| Some((metric, ratio?))) + [ + (Metric::Erosion.key(), self.erosion), + ("cognitive_complexity", self.cognitive_complexity), + (Metric::Duplication.key(), self.duplication), + (Metric::Verbosity.key(), self.verbosity), + (Metric::ImportCycles.key(), self.import_cycles), + ("boundaries", self.boundaries), + ("orphan_files", self.orphan_files), + (HAZARDS_METRIC_KEY, self.hazards), + ] + .into_iter() + .filter_map(|(metric, ratio)| Some((metric.to_owned(), ratio?))) } } @@ -2024,6 +2083,7 @@ fn regression_limits(file: RegressionLimitsFile) -> RegressionLimits { import_cycles, boundaries, orphan_files, + hazards, unused_dependencies, unlisted_dependencies, dev_in_production_dependencies, @@ -2051,6 +2111,7 @@ fn regression_limits(file: RegressionLimitsFile) -> RegressionLimits { import_cycles, boundaries, orphan_files, + hazards, external, } .by_metric() diff --git a/crates/config/src/codeint_json/starter.rs b/crates/config/src/codeint_json/starter.rs index e49bba50..3d69e28a 100644 --- a/crates/config/src/codeint_json/starter.rs +++ b/crates/config/src/codeint_json/starter.rs @@ -92,6 +92,8 @@ fn starter_configuration_text(languages: &[DetectedLanguage]) -> String { duplication: Default::default(), entry_points: Vec::new(), coverage_reports: Vec::new(), + sql: Default::default(), + hazards: Default::default(), languages: (!languages.is_empty()).then(|| { languages .iter() @@ -112,10 +114,16 @@ fn starter_configuration_text(languages: &[DetectedLanguage]) -> String { if let Some(root) = json.as_object_mut() { root.insert("coverage_reports".to_owned(), serde_json::json!([])); } - let rendered = format!("{json:#}\n"); - rendered.replacen( + let rendered = format!("{json:#}\n").replacen( " \"budgets\": {\n \"production\": {},", " \"budgets\": {\n \"production\": {\n // \"test_gap\": 0.2\n },", 1, - ) + ); + let has_sql = languages.iter().any(|language| language.plugin == "sql"); + if has_sql && let Some(prefix) = rendered.strip_suffix("}\n") { + return format!( + "{prefix} // Optional: map SQL folders to a Dialect with sql.dialects (postgresql, mysql, sqlite, or duckdb).\n // \"sql\": {{ \"dialects\": [] }}\n}}\n" + ); + } + rendered } diff --git a/crates/config/src/codeint_json/starter/tests.rs b/crates/config/src/codeint_json/starter/tests.rs index 8c790775..1acca58b 100644 --- a/crates/config/src/codeint_json/starter/tests.rs +++ b/crates/config/src/codeint_json/starter/tests.rs @@ -35,11 +35,30 @@ fn the_starter_configuration_passes_the_shape_check_of_the_published_schema_with let text = starter_configuration_text(languages); assert!(text.contains("\"coverage_reports\": []"), "{text}"); assert!(text.contains("// \"test_gap\": 0.2"), "{text}"); + assert!(!text.contains("sql.dialects"), "{text}"); let starter: Value = parse_jsonc(&text).expect("the starter configuration is valid JSONC"); shape::check_shape(&starter, &schema).expect("the starter configuration fits the schema"); let parsed = parse(&text).expect("the starter configuration parses cleanly"); assert!(parsed.budgets.production_test_gap().is_none()); assert!(parsed.coverage_reports.is_empty()); + assert!(parsed.sql.is_empty()); } } + +#[test] +fn the_starter_configuration_mentions_optional_sql_dialects_only_when_sql_is_detected() { + let schema = published_schema(); + let detected = [DetectedLanguage { + plugin: "sql".to_owned(), + include: vec![path("db")], + }]; + + let text = starter_configuration_text(&detected); + assert!(text.contains("sql.dialects"), "{text}"); + assert!(text.contains("// \"sql\": { \"dialects\": [] }"), "{text}"); + let starter: Value = parse_jsonc(&text).expect("the starter configuration is valid JSONC"); + shape::check_shape(&starter, &schema).expect("the starter configuration fits the schema"); + let parsed = parse(&text).expect("the starter configuration parses cleanly"); + assert!(parsed.sql.is_empty()); +} diff --git a/crates/config/src/config_error.rs b/crates/config/src/config_error.rs index 63f229a6..51053532 100644 --- a/crates/config/src/config_error.rs +++ b/crates/config/src/config_error.rs @@ -273,6 +273,16 @@ pub enum ConfigurationFileError { CliTestGapBudgetOutsideProduction { source_set: SourceSet }, #[error("{file}: {key} is not supported; Test gap has no Regression check")] TestGapRegressionLimit { file: ConfigFileKind, key: KeyPath }, + #[error("{file}: {key} for SQL dialect {dialect:?} must list at least one glob pattern")] + EmptySqlDialectInclude { + file: ConfigFileKind, + key: KeyPath, + dialect: String, + }, + #[error("{file}: {key} must not be empty")] + EmptySqlDialectPattern { file: ConfigFileKind, key: KeyPath }, + #[error("{file}: {key} must not be empty")] + EmptyHazardRuleName { file: ConfigFileKind, key: KeyPath }, } impl ConfigurationFileError { @@ -308,7 +318,10 @@ impl ConfigurationFileError { | AbsoluteCoverageReportPath { file, .. } | ParentTraversalCoverageReportPath { file, .. } | TestGapBudgetOutsideProduction { file, .. } - | TestGapRegressionLimit { file, .. } => *file = file_kind, + | TestGapRegressionLimit { file, .. } + | EmptySqlDialectInclude { file, .. } + | EmptySqlDialectPattern { file, .. } + | EmptyHazardRuleName { file, .. } => *file = file_kind, AmbiguousConfigFiles | UnknownCliBudgetMetric { .. } | CliTestGapBudgetOutsideProduction { .. } @@ -346,6 +359,13 @@ pub(crate) fn glob_set(key: &KeyPath, globs: &[String]) -> Result KeyPath { + KeyPath(vec![ + KeySegment::Key(parent.to_owned()), + KeySegment::Key(child.to_owned()), + ]) + } + pub(crate) fn child(&self, segment: KeySegment) -> KeyPath { let mut segments = self.0.clone(); segments.push(segment); diff --git a/crates/config/src/hazards.rs b/crates/config/src/hazards.rs new file mode 100644 index 00000000..d053c3c6 --- /dev/null +++ b/crates/config/src/hazards.rs @@ -0,0 +1,55 @@ +use std::collections::BTreeSet; + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use crate::config_error::{ConfigFileKind, ConfigurationFileError, KeyPath, KeySegment}; + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct HazardsConfig { + pub disabled_rules: Vec, +} + +impl HazardsConfig { + pub fn is_disabled(&self, rule: &str) -> bool { + self.disabled_rules.iter().any(|disabled| disabled == rule) + } + + pub fn disabled_rules_set(&self) -> BTreeSet { + self.disabled_rules.iter().cloned().collect() + } + + pub(crate) fn from_file( + file: HazardsConfigFile, + ) -> Result { + let base_key = KeyPath::nested("hazards", "disabled_rules"); + if let Some((index, _)) = file + .disabled_rules + .iter() + .enumerate() + .find(|(_, entry)| entry.trim().is_empty()) + { + return Err(ConfigurationFileError::EmptyHazardRuleName { + file: ConfigFileKind::Json, + key: base_key.child(KeySegment::Index(index)), + }); + } + Ok(HazardsConfig { + disabled_rules: file.disabled_rules, + }) + } +} + +#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub(crate) struct HazardsConfigFile { + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[schemars( + description = "Names of Hazard line rules turned off across the repository. A turned-off rule adds no Hazard line and no Finding." + )] + pub(crate) disabled_rules: Vec, +} + +pub(crate) fn is_hazards_unset(file: &HazardsConfigFile) -> bool { + file.disabled_rules.is_empty() +} diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 52ce4cc4..c29dcae3 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -14,9 +14,11 @@ mod codeowners; mod config_error; mod coupling; mod dependencies; +mod hazards; mod regression_limits; mod resolved; mod result_cache_folder; +mod sql; pub use boundaries::{ Boundaries, BoundaryDirective, BoundaryPreset, BoundaryRuleDecision, BoundarySourceSet, @@ -28,9 +30,9 @@ pub use cli_schema::{ }; pub use codeint_json::{ Budget, Budgets, Configuration, ConfigurationInspection, DEPENDENCY_METRIC_KEYS, - DetectedLanguage, DiscoveredConfigFile, DuplicationConfig, EntryPoints, LanguageCoverage, - Languages, MinSimilarity, PluginDeclaration, PluginKind, PluginLimits, PluginSource, - SchemaValueSpan, SchemaVersionStatus, Sha256Digest, SourceSetOverrides, + DetectedLanguage, DiscoveredConfigFile, DuplicationConfig, EntryPoints, HAZARDS_METRIC_KEY, + LanguageCoverage, Languages, MinSimilarity, PluginDeclaration, PluginKind, PluginLimits, + PluginSource, SchemaValueSpan, SchemaVersionStatus, Sha256Digest, SourceSetOverrides, StarterConfigurationError, TEST_GAP_METRIC_KEY, configuration_schema, discover_config_file, inspect_configuration, is_broken_symlink, published_schema_address, read_configuration, read_resolved_configuration, schema_value_span, write_starter_configuration, @@ -44,11 +46,13 @@ pub use coupling::{ DEFAULT_MIN_CO_CHANGES, DEFAULT_MIN_COUPLING_RATIO, }; pub use dependencies::DependenciesConfig; +pub use hazards::HazardsConfig; pub use regression_limits::{NewFindingsRule, RatioRise, RegressionLimit, RegressionLimits}; pub use resolved::{ BudgetOverride, ConfigOverrides, ConfigProvenance, ResolvedConfiguration, ResolvedSetting, SourceSetOverride, }; +pub use sql::{KNOWN_SQL_DIALECTS, SqlConfig, SqlDialect, SqlDialectConflict}; const DEFAULT_PLUGIN_DOWNLOAD_TIMEOUT_SECONDS: u64 = 60; diff --git a/crates/config/src/regression_limits.rs b/crates/config/src/regression_limits.rs index e3d8ef08..1fea03d2 100644 --- a/crates/config/src/regression_limits.rs +++ b/crates/config/src/regression_limits.rs @@ -164,6 +164,7 @@ impl RegressionLimits { && key != "cognitive_complexity" && key != "boundaries" && key != "orphan_files" + && key != crate::HAZARDS_METRIC_KEY && !crate::DEPENDENCY_METRIC_KEYS.contains(&key) { keys.insert(key.to_owned()); diff --git a/crates/config/src/sql.rs b/crates/config/src/sql.rs new file mode 100644 index 00000000..b4ceb504 --- /dev/null +++ b/crates/config/src/sql.rs @@ -0,0 +1,218 @@ +use std::fmt; + +use codeint_model::RepoPath; +use globset::GlobSet; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use crate::config_error::{ConfigFileKind, ConfigurationFileError, KeyPath, KeySegment, glob_set}; + +pub const KNOWN_SQL_DIALECTS: [&str; 4] = ["postgresql", "mysql", "sqlite", "duckdb"]; + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum SqlDialect { + #[default] + Generic, + Postgresql, + Mysql, + Sqlite, + Duckdb, +} + +impl SqlDialect { + pub fn as_str(self) -> &'static str { + match self { + SqlDialect::Generic => "generic", + SqlDialect::Postgresql => "postgresql", + SqlDialect::Mysql => "mysql", + SqlDialect::Sqlite => "sqlite", + SqlDialect::Duckdb => "duckdb", + } + } + + pub fn parse_configured(name: &str) -> Option { + match name { + "postgresql" => Some(SqlDialect::Postgresql), + "mysql" => Some(SqlDialect::Mysql), + "sqlite" => Some(SqlDialect::Sqlite), + "duckdb" => Some(SqlDialect::Duckdb), + _ => None, + } + } +} + +impl fmt::Display for SqlDialect { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(self.as_str()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error( + "{path} matches conflicting SQL dialects: {first_dialect} (pattern {first_pattern:?}) and {second_dialect} (pattern {second_pattern:?})" +)] +pub struct SqlDialectConflict { + pub path: RepoPath, + pub first_dialect: SqlDialect, + pub first_pattern: String, + pub second_dialect: SqlDialect, + pub second_pattern: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub(crate) enum ConfiguredSqlDialect { + Postgresql, + Mysql, + Sqlite, + Duckdb, +} + +impl ConfiguredSqlDialect { + fn into_dialect(self) -> SqlDialect { + match self { + ConfiguredSqlDialect::Postgresql => SqlDialect::Postgresql, + ConfiguredSqlDialect::Mysql => SqlDialect::Mysql, + ConfiguredSqlDialect::Sqlite => SqlDialect::Sqlite, + ConfiguredSqlDialect::Duckdb => SqlDialect::Duckdb, + } + } +} + +#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub(crate) struct SqlDialectEntryFile { + #[schemars( + description = "SQL Dialect for matching files: postgresql, mysql (including MariaDB), sqlite, or duckdb." + )] + dialect: ConfiguredSqlDialect, + #[schemars( + description = "Globs of repository-relative folders or files that use this SQL Dialect; a folder covers every file below it." + )] + include: Vec, +} + +#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub(crate) struct SqlConfigFile { + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[schemars( + description = "Folder or file patterns mapped to a SQL Dialect (postgresql, mysql, sqlite, or duckdb). Files covered by no entry use generic SQL." + )] + pub(crate) dialects: Vec, +} + +impl SqlConfigFile { + pub(crate) fn is_unset(&self) -> bool { + self.dialects.is_empty() + } +} + +#[derive(Debug)] +struct SqlDialectEntry { + dialect: SqlDialect, + patterns: Vec, + include: GlobSet, +} + +#[derive(Debug, Default)] +pub struct SqlConfig { + entries: Vec, +} + +impl SqlConfig { + pub(crate) fn from_file(file: SqlConfigFile) -> Result { + let dialects_key = KeyPath::nested("sql", "dialects"); + let entries = file + .dialects + .into_iter() + .enumerate() + .map(|(index, entry)| compile_dialect_entry(&dialects_key, index, entry)) + .collect::, _>>()?; + Ok(SqlConfig { entries }) + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + pub fn dialect_for(&self, path: &RepoPath) -> Result { + if self.entries.is_empty() { + return Ok(SqlDialect::Generic); + } + let candidates = path_and_ancestors(path); + let mut matched: Option<(SqlDialect, &str)> = None; + for entry in &self.entries { + let Some(pattern) = first_matching_pattern(entry, &candidates) else { + continue; + }; + match matched { + None => matched = Some((entry.dialect, pattern)), + Some((first_dialect, _)) if first_dialect == entry.dialect => {} + Some((first_dialect, first_pattern)) => { + return Err(SqlDialectConflict { + path: path.clone(), + first_dialect, + first_pattern: first_pattern.to_owned(), + second_dialect: entry.dialect, + second_pattern: pattern.to_owned(), + }); + } + } + } + Ok(matched.map_or(SqlDialect::Generic, |(dialect, _)| dialect)) + } +} + +fn compile_dialect_entry( + dialects_key: &KeyPath, + index: usize, + entry: SqlDialectEntryFile, +) -> Result { + let dialect = entry.dialect.into_dialect(); + let include_key = dialects_key + .child(KeySegment::Index(index)) + .child(KeySegment::Key("include".to_owned())); + if entry.include.is_empty() { + return Err(ConfigurationFileError::EmptySqlDialectInclude { + file: ConfigFileKind::Json, + key: include_key, + dialect: dialect.as_str().to_owned(), + }); + } + for (pattern_index, pattern) in entry.include.iter().enumerate() { + if pattern.trim().is_empty() { + return Err(ConfigurationFileError::EmptySqlDialectPattern { + file: ConfigFileKind::Json, + key: include_key.child(KeySegment::Index(pattern_index)), + }); + } + } + let include = glob_set(&include_key, &entry.include)?; + Ok(SqlDialectEntry { + dialect, + patterns: entry.include, + include, + }) +} + +fn path_and_ancestors(path: &RepoPath) -> Vec<&str> { + path.as_str() + .match_indices('/') + .map(|(end, _)| &path.as_str()[..end]) + .chain([path.as_str()]) + .collect() +} + +fn first_matching_pattern<'entry>( + entry: &'entry SqlDialectEntry, + candidates: &[&str], +) -> Option<&'entry str> { + for candidate in candidates { + if let Some(index) = entry.include.matches(candidate).into_iter().min() { + return Some(entry.patterns[index].as_str()); + } + } + None +} diff --git a/crates/config/tests/sql_hazards.rs b/crates/config/tests/sql_hazards.rs new file mode 100644 index 00000000..900324fb --- /dev/null +++ b/crates/config/tests/sql_hazards.rs @@ -0,0 +1,499 @@ +use std::collections::BTreeSet; +use std::path::PathBuf; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use codeint_config::{ + BudgetOverride, ConfigOverrides, ConfigProvenance, Configuration, ConfigurationFileError, + HAZARDS_METRIC_KEY, HazardsConfig, KNOWN_SQL_DIALECTS, NewFindingsRule, RatioRise, + RegressionLimit, ResolvedConfiguration, SqlDialect, SqlDialectConflict, configuration_schema, + read_configuration, read_resolved_configuration, +}; +use codeint_model::{RepoPath, SourceSet}; +use serde_json::{Value, json}; + +struct TempConfigRoot { + dir: PathBuf, +} + +impl TempConfigRoot { + fn empty() -> TempConfigRoot { + static COUNTER: AtomicUsize = AtomicUsize::new(0); + let dir = std::env::temp_dir() + .join("codeint-sql-hazards-tests") + .join(std::process::id().to_string()) + .join(COUNTER.fetch_add(1, Ordering::Relaxed).to_string()); + std::fs::create_dir_all(&dir).expect("create temp config root"); + TempConfigRoot { dir } + } + + fn create(file: Option<(&str, &str)>) -> TempConfigRoot { + let root = TempConfigRoot::empty(); + if let Some((name, content)) = file { + std::fs::write(root.dir.join(name), content).expect("write config file"); + } + root + } + + fn read(&self) -> Result { + read_configuration(&self.dir) + } + + fn resolve( + &self, + overrides: &ConfigOverrides, + ) -> Result { + read_resolved_configuration(&self.dir, overrides) + } +} + +impl Drop for TempConfigRoot { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +fn repo_path(path: &str) -> RepoPath { + RepoPath::new(path).expect("valid repo path") +} + +fn expect_invalid( + file_name: &str, + payload: &Value, + expected_substrings: &[&str], +) -> ConfigurationFileError { + let raw = payload.to_string(); + let err = TempConfigRoot::create(Some((file_name, &raw))) + .read() + .expect_err("expected config error"); + let message = err.to_string(); + for needle in expected_substrings { + assert!( + message.contains(needle), + "expected {needle:?} in {message:?}" + ); + } + err +} + +#[test] +fn sql_dialects_defaults_to_generic_and_resolves_folder_file_and_multi_dialect_mappings() { + assert_eq!( + KNOWN_SQL_DIALECTS, + ["postgresql", "mysql", "sqlite", "duckdb"] + ); + assert_eq!(SqlDialect::default(), SqlDialect::Generic); + assert_eq!(SqlDialect::Generic.as_str(), "generic"); + for (name, expected) in [ + ("postgresql", Some(SqlDialect::Postgresql)), + ("mysql", Some(SqlDialect::Mysql)), + ("sqlite", Some(SqlDialect::Sqlite)), + ("duckdb", Some(SqlDialect::Duckdb)), + ("generic", None), + ("oracle", None), + ] { + assert_eq!(SqlDialect::parse_configured(name), expected); + } + + let default_config = Configuration::default(); + assert!(default_config.sql.is_empty()); + assert_eq!( + default_config.sql.dialect_for(&repo_path("db/query.sql")), + Ok(SqlDialect::Generic) + ); + + let raw = json!({ + "sql": { + "dialects": [ + { "dialect": "postgresql", "include": ["db/pg", "shared/pg_*.sql"] }, + { "dialect": "postgresql", "include": ["db/pg/migrations/**"] }, + { "dialect": "mysql", "include": ["db/mysql/**"] }, + { "dialect": "sqlite", "include": ["mobile/local.sql"] }, + { "dialect": "duckdb", "include": ["analytics"] } + ] + } + }) + .to_string(); + + let resolved = TempConfigRoot::create(Some(("codeint.json", &raw))) + .resolve(&ConfigOverrides::default()) + .expect("valid multi-dialect config"); + let sql = &resolved.configuration.sql; + assert!(!sql.is_empty()); + for (path, expected) in [ + ("db/pg/migrations/001.sql", SqlDialect::Postgresql), + ("shared/pg_views.sql", SqlDialect::Postgresql), + ("db/mysql/init.sql", SqlDialect::Mysql), + ("mobile/local.sql", SqlDialect::Sqlite), + ("analytics/monthly/revenue.sql", SqlDialect::Duckdb), + ("db/pg_other/schema.sql", SqlDialect::Generic), + ("unmapped/query.sql", SqlDialect::Generic), + ] { + assert_eq!(sql.dialect_for(&repo_path(path)), Ok(expected), "{path}"); + } + + let setting = resolved + .settings + .iter() + .find(|item| item.key == "sql.dialects") + .expect("sql.dialects setting present"); + assert_eq!(setting.source, ConfigProvenance::File); + assert_eq!(setting.value.as_array().map(Vec::len), Some(5)); +} + +#[test] +fn sql_dialect_conflict_reports_both_patterns_and_dialects() { + let raw = json!({ + "sql": { + "dialects": [ + { "dialect": "postgresql", "include": ["db/**"] }, + { "dialect": "duckdb", "include": ["db/analytics/**"] } + ] + } + }) + .to_string(); + + let config = TempConfigRoot::create(Some(("codeint.json", &raw))) + .read() + .expect("syntactically valid config"); + let conflict = config + .sql + .dialect_for(&repo_path("db/analytics/report.sql")) + .expect_err("overlapping different dialects must conflict"); + assert_eq!( + conflict, + SqlDialectConflict { + path: repo_path("db/analytics/report.sql"), + first_dialect: SqlDialect::Postgresql, + first_pattern: "db/**".to_owned(), + second_dialect: SqlDialect::Duckdb, + second_pattern: "db/analytics/**".to_owned(), + } + ); + let rendered = conflict.to_string(); + for expected in [ + "db/analytics/report.sql", + "postgresql", + "db/**", + "duckdb", + "db/analytics/**", + ] { + assert!(rendered.contains(expected), "{rendered}"); + } +} + +#[test] +fn sql_dialects_rejects_unknown_dialect_empty_include_empty_pattern_and_invalid_glob() { + let err = expect_invalid( + "codeint.jsonc", + &json!({ + "sql": { + "dialects": [ + { "dialect": "postgresql", "include": ["db/pg/**"] }, + { "dialect": "oracle", "include": ["db/ora/**"] } + ] + } + }), + &[ + "codeint.jsonc", + "sql.dialects[1].dialect", + "postgresql, mysql, sqlite, duckdb", + "oracle", + ], + ); + assert!(matches!(err, ConfigurationFileError::NotOneOf { .. })); + + let generic_err = expect_invalid( + "codeint.json", + &json!({ "sql": { "dialects": [{ "dialect": "generic", "include": ["db/**"] }] } }), + &[ + "sql.dialects[0].dialect", + "postgresql, mysql, sqlite, duckdb", + ], + ); + assert!(matches!( + generic_err, + ConfigurationFileError::NotOneOf { .. } + )); + + let empty_include_err = expect_invalid( + "codeint.json", + &json!({ "sql": { "dialects": [{ "dialect": "sqlite", "include": [] }] } }), + &["sql.dialects[0].include", "sqlite"], + ); + assert!(matches!( + empty_include_err, + ConfigurationFileError::EmptySqlDialectInclude { .. } + )); + + let empty_pattern_err = expect_invalid( + "codeint.json", + &json!({ "sql": { "dialects": [{ "dialect": "mysql", "include": ["db/**", " "] }] } }), + &["sql.dialects[0].include[1]"], + ); + assert!(matches!( + empty_pattern_err, + ConfigurationFileError::EmptySqlDialectPattern { .. } + )); + + let bad_glob_err = expect_invalid( + "codeint.json", + &json!({ "sql": { "dialects": [{ "dialect": "duckdb", "include": ["db/[unclosed"] }] } }), + &["sql.dialects[0].include[0]"], + ); + assert!(matches!( + bad_glob_err, + ConfigurationFileError::InvalidGlob { .. } + )); +} + +#[test] +fn hazards_disabled_rules_defaults_empty_parses_and_rejects_empty_entries() { + assert_eq!(Configuration::default().hazards, HazardsConfig::default()); + assert!(!Configuration::default().hazards.is_disabled("select-star")); + assert!( + Configuration::default() + .hazards + .disabled_rules_set() + .is_empty() + ); + + let default_resolved = TempConfigRoot::create(None) + .resolve(&ConfigOverrides::default()) + .expect("default config"); + let default_setting = default_resolved + .settings + .iter() + .find(|item| item.key == "hazards.disabled_rules") + .expect("hazards.disabled_rules default setting"); + assert_eq!(default_setting.value, json!([])); + assert_eq!(default_setting.source, ConfigProvenance::Default); + + let raw = json!({ + "hazards": { "disabled_rules": ["select-star", "large-offset", "select-star"] } + }) + .to_string(); + let resolved = TempConfigRoot::create(Some(("codeint.json", &raw))) + .resolve(&ConfigOverrides::default()) + .expect("valid hazards config"); + assert!(resolved.configuration.hazards.is_disabled("select-star")); + assert!(resolved.configuration.hazards.is_disabled("large-offset")); + assert!(!resolved.configuration.hazards.is_disabled("drop")); + assert_eq!( + resolved.configuration.hazards.disabled_rules_set(), + BTreeSet::from(["large-offset".to_owned(), "select-star".to_owned()]) + ); + + let file_setting = resolved + .settings + .iter() + .find(|item| item.key == "hazards.disabled_rules") + .expect("hazards.disabled_rules file setting"); + assert_eq!(file_setting.source, ConfigProvenance::File); + assert_eq!( + file_setting.value, + json!(["select-star", "large-offset", "select-star"]) + ); + + for empty in ["", " "] { + let err = expect_invalid( + "codeint.jsonc", + &json!({ "hazards": { "disabled_rules": [empty] } }), + &["codeint.jsonc", "hazards.disabled_rules[0]"], + ); + assert!(matches!( + err, + ConfigurationFileError::EmptyHazardRuleName { .. } + )); + } +} + +#[test] +fn hazards_budgets_work_across_all_four_source_sets_and_cli_overrides() { + assert_eq!(HAZARDS_METRIC_KEY, "hazards"); + let raw = json!({ + "budgets": { + "production": { "hazards": 0.05 }, + "test": { "hazards": 0.25 }, + "generated": { "hazards": 0.5 }, + "vendored": { "hazards": 1.0 } + } + }) + .to_string(); + let config = TempConfigRoot::create(Some(("codeint.json", &raw))) + .read() + .expect("valid hazards budgets"); + config + .validate_metrics(&[]) + .expect("hazards is a known built-in metric key"); + for (source_set, expected) in [ + (SourceSet::Production, 0.05), + (SourceSet::Test, 0.25), + (SourceSet::Generated, 0.5), + (SourceSet::Vendored, 1.0), + ] { + assert_eq!( + config + .budgets + .budget_for_key(source_set, HAZARDS_METRIC_KEY) + .map(|budget| budget.ratio()), + Some(expected) + ); + } + + for invalid in [-0.01_f64, 1.01_f64] { + let err = expect_invalid( + "codeint.json", + &json!({ "budgets": { "production": { "hazards": invalid } } }), + &["budgets.production.hazards"], + ); + assert!(matches!(err, ConfigurationFileError::OutOfRange { .. })); + } + + let cli_budgets: Vec = ["production.hazards=0.1", "generated.hazards=0.4"] + .into_iter() + .map(|spec| spec.parse().expect("valid cli budget")) + .collect(); + let overrides = ConfigOverrides { + budgets: cli_budgets, + ..ConfigOverrides::default() + }; + let resolved = TempConfigRoot::create(None) + .resolve(&overrides) + .expect("resolved with CLI hazards budgets"); + resolved + .configuration + .validate_cli_budget_metrics(&overrides.budgets, &[]) + .expect("hazards CLI overrides are valid"); + resolved + .configuration + .validate_metrics(&[]) + .expect("resolved config is valid"); + assert_eq!( + resolved + .configuration + .budgets + .budget_for_key(SourceSet::Production, HAZARDS_METRIC_KEY) + .map(|budget| budget.ratio()), + Some(0.1) + ); + assert_eq!( + resolved + .configuration + .budgets + .budget_for_key(SourceSet::Generated, HAZARDS_METRIC_KEY) + .map(|budget| budget.ratio()), + Some(0.4) + ); +} + +#[test] +fn hazards_regression_limits_default_and_override_globally_and_per_source_set() { + let default_resolved = TempConfigRoot::create(None) + .resolve(&ConfigOverrides::default()) + .expect("default"); + for source_set in [ + SourceSet::Production, + SourceSet::Test, + SourceSet::Generated, + SourceSet::Vendored, + ] { + assert_eq!( + default_resolved + .configuration + .regression_limits + .limit_for_key(source_set, HAZARDS_METRIC_KEY), + RegressionLimit::DEFAULT + ); + } + + let raw = json!({ + "regression_limits": { + "hazards": { "ratio_rise": 0.02, "new_findings": "any_new_finding" }, + "test": { "hazards": { "new_findings": "never" } } + } + }) + .to_string(); + let resolved = TempConfigRoot::create(Some(("codeint.json", &raw))) + .resolve(&ConfigOverrides::default()) + .expect("valid hazards regression limits"); + resolved + .configuration + .validate_metrics(&[]) + .expect("hazards regression limits pass validation"); + + let prod_limit = resolved + .configuration + .regression_limits + .limit_for_key(SourceSet::Production, HAZARDS_METRIC_KEY); + assert_eq!(prod_limit.ratio_rise.ratio(), 0.02); + assert_eq!(prod_limit.new_findings, NewFindingsRule::AnyNewFinding); + + let test_limit = resolved + .configuration + .regression_limits + .limit_for_key(SourceSet::Test, HAZARDS_METRIC_KEY); + assert_eq!(test_limit.ratio_rise.ratio(), 0.02); + assert_eq!(test_limit.new_findings, NewFindingsRule::Never); + + let prod_ratio_settings: Vec<_> = resolved + .settings + .iter() + .filter(|item| item.key == "regression_limits.production.hazards.ratio_rise") + .collect(); + assert_eq!(prod_ratio_settings.len(), 1); + assert_eq!(prod_ratio_settings[0].value, json!(0.02)); + assert_eq!(prod_ratio_settings[0].source, ConfigProvenance::File); + + let default_ratio_setting = default_resolved + .settings + .iter() + .find(|item| item.key == "regression_limits.production.hazards.ratio_rise") + .expect("default hazards ratio_rise present"); + assert_eq!( + default_ratio_setting.value, + json!(RatioRise::DEFAULT.ratio()) + ); + assert_eq!(default_ratio_setting.source, ConfigProvenance::Default); +} + +#[test] +fn empty_sql_and_hazards_sections_serialize_identically_to_default() { + let explicit_empty = TempConfigRoot::create(Some(( + "codeint.json", + r#"{ "sql": { "dialects": [] }, "hazards": { "disabled_rules": [] } }"#, + ))) + .read() + .expect("empty sql and hazards sections parse"); + assert_eq!( + serde_json::to_string(&Configuration::default()).expect("serialize default"), + serde_json::to_string(&explicit_empty).expect("serialize explicit empty") + ); +} + +#[test] +fn configuration_schema_exposes_sql_hazards_budgets_and_regression_limits() { + let schema: Value = serde_json::from_str(&configuration_schema()).expect("valid JSON schema"); + + assert_eq!(schema["properties"]["sql"]["$ref"], "#/$defs/SqlConfigFile"); + assert_eq!( + schema["properties"]["hazards"]["$ref"], + "#/$defs/HazardsConfigFile" + ); + assert_eq!( + schema["$defs"]["ConfiguredSqlDialect"]["enum"], + json!(["postgresql", "mysql", "sqlite", "duckdb"]) + ); + for def_name in [ + "ProductionMetricBudgets", + "MetricBudgets", + "RegressionLimitsFile", + "MetricRegressionLimits", + ] { + assert!( + schema["$defs"][def_name]["properties"] + .get("hazards") + .is_some(), + "missing hazards in {def_name}" + ); + } +} diff --git a/crates/metrics/src/hazards.rs b/crates/metrics/src/hazards.rs new file mode 100644 index 00000000..f1347de2 --- /dev/null +++ b/crates/metrics/src/hazards.rs @@ -0,0 +1,156 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use codeint_model::{CodeModel, Package, RepoPath, SourceFile, Token, token_text_hash}; + +use crate::FindingId; +use crate::finding_id::FindingIds; + +#[cfg(test)] +mod tests; + +pub const HAZARDS_METRIC_KEY: &str = "hazards"; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct HazardLines { + pub hazard_lines: u64, + pub source_lines: u64, +} + +impl HazardLines { + fn add(&mut self, other: HazardLines) { + self.hazard_lines += other.hazard_lines; + self.source_lines += other.source_lines; + } + + pub fn ratio(&self) -> f64 { + if self.source_lines == 0 { + 0.0 + } else { + self.hazard_lines as f64 / self.source_lines as f64 + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HazardLineFinding { + pub id: FindingId, + pub path: RepoPath, + pub line: u32, + pub rule: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Hazards { + totals: HazardLines, + lines_by_file: BTreeMap, + findings: Vec, +} + +impl Hazards { + pub fn measure(model: &CodeModel, disabled_rules: &BTreeSet) -> Option { + if !model.languages.iter().any(|facts| facts.has_hazard_rules) { + return None; + } + let per_file = group_files_in_path_order(model); + let mut lines_by_file = BTreeMap::new(); + let mut findings = Vec::new(); + let mut totals = HazardLines::default(); + let mut ids = FindingIds::for_key(HAZARDS_METRIC_KEY); + for (path, group) in per_file { + let file_lines = + measure_grouped_file(path, &group, disabled_rules, &mut ids, &mut findings); + totals.add(file_lines); + lines_by_file.insert(path.clone(), file_lines); + } + Some(Hazards { + totals, + lines_by_file, + findings, + }) + } + + pub fn by_package<'model>( + &self, + model: &'model CodeModel, + ) -> BTreeMap, HazardLines> { + let mut grouped: BTreeMap, HazardLines> = BTreeMap::new(); + for (path, &lines) in &self.lines_by_file { + grouped + .entry(model.workspace.package_of(path)) + .or_default() + .add(lines); + } + grouped + } + + pub fn totals(&self) -> HazardLines { + self.totals + } + + pub fn hazard_lines(&self) -> u64 { + self.totals.hazard_lines + } + + pub fn source_lines(&self) -> u64 { + self.totals.source_lines + } + + pub fn ratio(&self) -> f64 { + self.totals.ratio() + } + + pub fn findings(&self) -> &[HazardLineFinding] { + &self.findings + } +} + +fn group_files_in_path_order(model: &CodeModel) -> BTreeMap<&RepoPath, Vec<&SourceFile>> { + let mut grouped: BTreeMap<&RepoPath, Vec<&SourceFile>> = BTreeMap::new(); + for file in &model.files { + grouped.entry(&file.path).or_default().push(file); + } + grouped +} + +fn measure_grouped_file( + path: &RepoPath, + files: &[&SourceFile], + disabled_rules: &BTreeSet, + ids: &mut FindingIds, + findings: &mut Vec, +) -> HazardLines { + let source_lines: u64 = files + .iter() + .map(|file| u64::from(file.model.source_lines)) + .sum(); + let active_rules: BTreeSet<(u32, &str)> = files + .iter() + .flat_map(|file| file.model.hazard_lines.iter()) + .filter(|hazard| !disabled_rules.contains(hazard.rule.as_str())) + .map(|hazard| (hazard.line, hazard.rule.as_str())) + .collect(); + let distinct_lines: BTreeSet = active_rules.iter().map(|&(line, _)| line).collect(); + let tokens = files + .first() + .map(|file| file.model.tokens.as_slice()) + .unwrap_or_default(); + for (line, rule) in active_rules { + let content = std::iter::once(token_text_hash(rule)).chain(line_token_hashes(tokens, line)); + findings.push(HazardLineFinding { + id: ids.next_in_source_order([path], content), + path: path.clone(), + line, + rule: rule.to_owned(), + }); + } + HazardLines { + hazard_lines: distinct_lines.len() as u64, + source_lines, + } +} + +fn line_token_hashes(tokens: &[Token], line: u32) -> impl Iterator + '_ { + let start = tokens.partition_point(|token| token.line < line); + let end = tokens.partition_point(|token| token.line <= line); + tokens[start..end].iter().map(|token| token.text_hash) +} diff --git a/crates/metrics/src/hazards/tests.rs b/crates/metrics/src/hazards/tests.rs new file mode 100644 index 00000000..911effa0 --- /dev/null +++ b/crates/metrics/src/hazards/tests.rs @@ -0,0 +1,242 @@ +use std::collections::BTreeSet; + +use codeint_model::{ + CodeModel, HazardLine, LanguageFacts, Package, SourceFile, SourceSet, Token, TokenKind, + Workspace, token_text_hash, +}; + +use super::{HAZARDS_METRIC_KEY, HazardLines, Hazards}; +use crate::test_support::{empty_source_file, repo_path}; + +fn language_facts(language: &str, has_hazard_rules: bool, has_imports: bool) -> LanguageFacts { + LanguageFacts { + language: language.to_owned(), + has_coverage: false, + has_hazard_rules, + has_imports, + } +} + +fn sql_file(path: &str, source_lines: u32, hazards: &[(u32, &str)]) -> SourceFile { + let mut file = empty_source_file(path, SourceSet::Production, source_lines); + file.model.hazard_lines = hazards + .iter() + .map(|&(line, rule)| HazardLine { + line, + rule: rule.to_owned(), + }) + .collect(); + file +} + +fn with_tokens(mut file: SourceFile, pairs: &[(u32, &str)]) -> SourceFile { + file.model.tokens = pairs + .iter() + .map(|&(line, text)| Token { + kind: TokenKind::Other, + text_hash: token_text_hash(text), + line, + }) + .collect(); + file +} + +fn sql_model(files: Vec, workspace: Workspace) -> CodeModel { + CodeModel { + files, + workspace, + languages: vec![language_facts("sql", true, false)], + ..CodeModel::default() + } +} + +fn measure_sql(files: Vec, disabled: &[&str]) -> Hazards { + let disabled_set: BTreeSet = disabled.iter().map(|rule| (*rule).to_owned()).collect(); + Hazards::measure(&sql_model(files, Workspace::default()), &disabled_set) + .expect("Hazards must be present for SQL model") +} + +fn finding_triples(hazards: &Hazards) -> Vec<(&str, u32, &str)> { + hazards + .findings() + .iter() + .map(|item| (item.path.as_str(), item.line, item.rule.as_str())) + .collect() +} + +#[test] +fn hazards_is_absent_when_no_language_has_hazard_rules() { + assert_eq!(HAZARDS_METRIC_KEY, "hazards"); + let none_disabled = BTreeSet::new(); + assert_eq!( + Hazards::measure(&CodeModel::default(), &none_disabled), + None + ); + + let ts_model = CodeModel { + files: vec![empty_source_file("src/app.ts", SourceSet::Production, 20)], + languages: vec![language_facts("typescript-javascript", false, true)], + ..CodeModel::default() + }; + assert_eq!(Hazards::measure(&ts_model, &none_disabled), None); +} + +#[test] +fn hazards_reports_zero_ratio_for_clean_or_empty_sql() { + let clean = measure_sql(vec![sql_file("db/schema.sql", 12, &[])], &[]); + assert_eq!( + clean.totals(), + HazardLines { + hazard_lines: 0, + source_lines: 12, + } + ); + assert_eq!(clean.ratio(), 0.0); + assert!(clean.findings().is_empty()); + + let empty = measure_sql(vec![sql_file("db/empty.sql", 0, &[])], &[]); + assert_eq!(empty.ratio(), 0.0); + assert_eq!(empty.hazard_lines(), 0); + assert_eq!(empty.source_lines(), 0); +} + +#[test] +fn a_line_matching_multiple_rules_counts_once_and_emits_sorted_distinct_findings() { + let measured = measure_sql( + vec![ + sql_file( + "db/z.sql", + 6, + &[ + (4, "select-star"), + (4, "count-without-filter"), + (4, "select-star"), + ], + ), + sql_file("db/a.sql", 4, &[(2, "delete-without-filter")]), + ], + &[], + ); + + assert_eq!(measured.hazard_lines(), 2); + assert_eq!(measured.source_lines(), 10); + assert_eq!(measured.ratio(), 0.2); + assert_eq!( + finding_triples(&measured), + [ + ("db/a.sql", 2, "delete-without-filter"), + ("db/z.sql", 4, "count-without-filter"), + ("db/z.sql", 4, "select-star"), + ] + ); +} + +#[test] +fn disabled_rules_are_excluded_from_both_numerator_and_findings() { + let files = vec![sql_file( + "db/queries.sql", + 10, + &[ + (2, "select-star"), + (2, "select-without-filter-or-limit"), + (5, "select-star"), + ], + )]; + + let partial = measure_sql(files.clone(), &["select-star"]); + assert_eq!(partial.hazard_lines(), 1); + assert_eq!(partial.ratio(), 0.1); + assert_eq!( + finding_triples(&partial), + [("db/queries.sql", 2, "select-without-filter-or-limit")] + ); + + let all_off = measure_sql(files, &["select-star", "select-without-filter-or-limit"]); + assert_eq!(all_off.hazard_lines(), 0); + assert_eq!(all_off.source_lines(), 10); + assert!(all_off.findings().is_empty()); +} + +#[test] +fn by_package_aggregates_only_packages_with_hazard_capable_files() { + let api_root = repo_path("packages/api"); + let web_root = repo_path("packages/web"); + let workspace = Workspace::new([api_root.clone(), web_root.clone()]); + let model = sql_model( + vec![ + sql_file("migrations/001.sql", 4, &[(1, "drop")]), + sql_file( + "packages/api/queries.sql", + 6, + &[(2, "select-star"), (5, "truncate")], + ), + ], + workspace, + ); + + let measured = Hazards::measure(&model, &BTreeSet::new()).expect("Hazards present"); + let packages = measured.by_package(&model); + + assert_eq!( + packages.get(&Package::Root).copied(), + Some(HazardLines { + hazard_lines: 1, + source_lines: 4, + }) + ); + assert_eq!( + packages.get(&Package::Member(&api_root)).copied(), + Some(HazardLines { + hazard_lines: 2, + source_lines: 6, + }) + ); + assert_eq!(packages.get(&Package::Member(&web_root)), None); + + let summed_hazards: u64 = packages.values().map(|entry| entry.hazard_lines).sum(); + let summed_source: u64 = packages.values().map(|entry| entry.source_lines).sum(); + assert_eq!(summed_hazards, measured.hazard_lines()); + assert_eq!(summed_source, measured.source_lines()); +} + +#[test] +fn finding_id_stays_stable_when_line_moves_and_distinguishes_duplicate_occurrences() { + let pair_at = |line_a: u32, line_b: u32, total_lines: u32| { + let file = with_tokens( + sql_file( + "db/queries.sql", + total_lines, + &[(line_a, "select-star"), (line_b, "select-star")], + ), + &[ + (line_a, "SELECT"), + (line_a, "*"), + (line_b, "SELECT"), + (line_b, "*"), + ], + ); + measure_sql(vec![file], &[]) + }; + + let original = pair_at(2, 6, 10); + let shifted = pair_at(12, 16, 20); + assert_eq!(original.findings().len(), 2); + assert_ne!(original.findings()[0].id, original.findings()[1].id); + assert_eq!(original.findings()[0].id, shifted.findings()[0].id); + assert_eq!(original.findings()[1].id, shifted.findings()[1].id); +} + +#[test] +fn finding_debug_output_contains_no_source_text() { + let secret = "super-secret-password-value"; + let file = with_tokens( + sql_file("db/secrets.sql", 3, &[(2, "plain-text-secret")]), + &[(2, "PASSWORD"), (2, secret)], + ); + + let measured = measure_sql(vec![file], &[]); + let rendered = format!("{:?}", measured.findings()); + assert!(!rendered.contains(secret), "{rendered}"); + assert!(rendered.contains("plain-text-secret"), "{rendered}"); + assert!(rendered.contains("db/secrets.sql"), "{rendered}"); +} diff --git a/crates/metrics/src/lib.rs b/crates/metrics/src/lib.rs index 100e8e64..ea3ebdad 100644 --- a/crates/metrics/src/lib.rs +++ b/crates/metrics/src/lib.rs @@ -7,6 +7,7 @@ mod dependencies; mod duplication; mod erosion; mod finding_id; +mod hazards; mod impact; mod import_cycles; mod line_share; @@ -39,6 +40,7 @@ pub use duplication::{ }; pub use erosion::{ErodedFunction, Erosion, FunctionMasses}; pub use finding_id::FindingId; +pub use hazards::{HAZARDS_METRIC_KEY, HazardLineFinding, HazardLines, Hazards}; pub use impact::{ImpactAnalysis, ImpactDependent, ImpactError, ImpactSummary, ImpactTarget}; pub use import_cycles::{ImportCycle, ImportCycles, ModuleShare, UnresolvedImport}; pub use line_share::LineShare; diff --git a/crates/plugin-host/src/wasm_metric.rs b/crates/plugin-host/src/wasm_metric.rs index fb2dcf15..79fe202d 100644 --- a/crates/plugin-host/src/wasm_metric.rs +++ b/crates/plugin-host/src/wasm_metric.rs @@ -44,7 +44,7 @@ mod bindings { use bindings::codeint::plugin::language as guest_language; use bindings::exports::codeint::plugin::metric as guest_metric; -const RESERVED_KEYS: [&str; 10] = [ +const RESERVED_KEYS: [&str; 11] = [ "files", "source_lines", "packages", @@ -55,6 +55,7 @@ const RESERVED_KEYS: [&str; 10] = [ "unlisted_dependencies", "dev_in_production_dependencies", "test_gap", + "hazards", ]; #[cfg(test)] diff --git a/crates/plugin-host/src/wasm_metric/tests.rs b/crates/plugin-host/src/wasm_metric/tests.rs index 5b9a10b8..a3fda133 100644 --- a/crates/plugin-host/src/wasm_metric/tests.rs +++ b/crates/plugin-host/src/wasm_metric/tests.rs @@ -5,6 +5,7 @@ use crate::PluginHostError; fn rejects_test_gap_and_other_built_in_metric_keys_as_reserved() { for reserved in [ "test_gap", + "hazards", "erosion", "duplication", "verbosity", diff --git a/schema/codeint.schema.json b/schema/codeint.schema.json index dfb6c232..3276201b 100644 --- a/schema/codeint.schema.json +++ b/schema/codeint.schema.json @@ -81,6 +81,14 @@ "type": "string" }, "description": "Paths relative to the repository root of LCOV or Cobertura XML Coverage reports used to measure Test gap." + }, + "sql": { + "$ref": "#/$defs/SqlConfigFile", + "description": "SQL settings, including Dialect mappings for folders or files." + }, + "hazards": { + "$ref": "#/$defs/HazardsConfigFile", + "description": "Hazards Metric settings, including Hazard line rules turned off across the repository." } }, "title": "codeint.json", @@ -224,6 +232,13 @@ "minimum": 0, "maximum": 1 }, + "hazards": { + "type": "number", + "format": "double", + "description": "The highest Hazards ratio, from 0 to 1.", + "minimum": 0, + "maximum": 1 + }, "test_gap": { "type": "number", "format": "double", @@ -293,6 +308,13 @@ "description": "The highest Orphan files ratio, from 0 to 1.", "minimum": 0, "maximum": 1 + }, + "hazards": { + "type": "number", + "format": "double", + "description": "The highest Hazards ratio, from 0 to 1.", + "minimum": 0, + "maximum": 1 } }, "additionalProperties": { @@ -330,6 +352,10 @@ "$ref": "#/$defs/RegressionLimitSetting", "description": "The Regression limit of Orphan files in every Source set." }, + "hazards": { + "$ref": "#/$defs/RegressionLimitSetting", + "description": "The Regression limit of Hazards in every Source set." + }, "unused_dependencies": { "$ref": "#/$defs/RegressionLimitSetting", "description": "The Regression limit of unused declared dependencies." @@ -418,6 +444,10 @@ "orphan_files": { "$ref": "#/$defs/RegressionLimitSetting", "description": "The Regression limit of Orphan files in this Source set." + }, + "hazards": { + "$ref": "#/$defs/RegressionLimitSetting", + "description": "The Regression limit of Hazards in this Source set." } }, "additionalProperties": { @@ -652,6 +682,62 @@ "exclusiveMinimum": 0 } } + }, + "SqlConfigFile": { + "type": "object", + "additionalProperties": false, + "properties": { + "dialects": { + "type": "array", + "items": { + "$ref": "#/$defs/SqlDialectEntryFile" + }, + "description": "Folder or file patterns mapped to a SQL Dialect (postgresql, mysql, sqlite, or duckdb). Files covered by no entry use generic SQL." + } + } + }, + "SqlDialectEntryFile": { + "type": "object", + "additionalProperties": false, + "properties": { + "dialect": { + "$ref": "#/$defs/ConfiguredSqlDialect", + "description": "SQL Dialect for matching files: postgresql, mysql (including MariaDB), sqlite, or duckdb." + }, + "include": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Globs of repository-relative folders or files that use this SQL Dialect; a folder covers every file below it." + } + }, + "required": [ + "dialect", + "include" + ] + }, + "ConfiguredSqlDialect": { + "type": "string", + "enum": [ + "postgresql", + "mysql", + "sqlite", + "duckdb" + ] + }, + "HazardsConfigFile": { + "type": "object", + "additionalProperties": false, + "properties": { + "disabled_rules": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Names of Hazard line rules turned off across the repository. A turned-off rule adds no Hazard line and no Finding." + } + } } } } From e6729614add176678456b27a7632c3e6af72e249 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Tue, 24 Nov 2026 21:03:09 +0800 Subject: [PATCH 02/12] feat(plugins): add SQL Language plugin core for generic SQL and four Dialects --- Cargo.lock | 87 +- Cargo.toml | 2 + plugins/languages/sql/Cargo.toml | 13 + plugins/languages/sql/src/flagged.rs | 715 +++++++++++++++++ plugins/languages/sql/src/lib.rs | 255 ++++++ plugins/languages/sql/src/parser.rs | 35 + plugins/languages/sql/src/source_set.rs | 231 ++++++ plugins/languages/sql/src/statements.rs | 879 +++++++++++++++++++++ plugins/languages/sql/src/tokenize.rs | 594 ++++++++++++++ plugins/languages/sql/tests/conformance.rs | 658 +++++++++++++++ 10 files changed, 3465 insertions(+), 4 deletions(-) create mode 100644 plugins/languages/sql/Cargo.toml create mode 100644 plugins/languages/sql/src/flagged.rs create mode 100644 plugins/languages/sql/src/lib.rs create mode 100644 plugins/languages/sql/src/parser.rs create mode 100644 plugins/languages/sql/src/source_set.rs create mode 100644 plugins/languages/sql/src/statements.rs create mode 100644 plugins/languages/sql/src/tokenize.rs create mode 100644 plugins/languages/sql/tests/conformance.rs diff --git a/Cargo.lock b/Cargo.lock index b7fb1e9a..4b196c66 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -93,6 +93,15 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "ar_archive_writer" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" +dependencies = [ + "object 0.39.1", +] + [[package]] name = "arbitrary" version = "1.5.0" @@ -376,6 +385,14 @@ dependencies = [ "toml", ] +[[package]] +name = "codeint-lang-sql" +version = "0.6.0" +dependencies = [ + "codeint-model", + "sqlparser", +] + [[package]] name = "codeint-lang-ts" version = "0.6.0" @@ -2179,6 +2196,15 @@ dependencies = [ "autocfg", ] +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + [[package]] name = "object" version = "0.40.0" @@ -2573,6 +2599,16 @@ dependencies = [ "parking_lot", ] +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + [[package]] name = "pulley-interpreter" version = "51.0.0" @@ -2631,6 +2667,26 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "recursive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0786a43debb760f491b1bc0269fe5e84155353c67482b9e60d0cfb596054b43e" +dependencies = [ + "recursive-proc-macro-impl", + "stacker", +] + +[[package]] +name = "recursive-proc-macro-impl" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76009fbe0614077fc1a2ce255e3a1881a2e3a3527097d5dc6d8212c585e7e38b" +dependencies = [ + "quote", + "syn 2.0.119", +] + [[package]] name = "redox_syscall" version = "0.5.18" @@ -2938,12 +2994,35 @@ version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8e2fb0f499abb4d162f2bedad68f5ef91a1682b5a03596ddb67efd37768d100" +[[package]] +name = "sqlparser" +version = "0.64.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e0d273b4f8ddd14a35ed36862acbc9cc96cec578e36ee1881a9d42e0e0f2c8" +dependencies = [ + "log", + "recursive", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys", +] + [[package]] name = "static_assertions" version = "1.1.0" @@ -3339,7 +3418,7 @@ dependencies = [ "log", "mach2", "memfd", - "object", + "object 0.40.0", "once_cell", "postcard", "pulley-interpreter", @@ -3378,7 +3457,7 @@ dependencies = [ "hashbrown 0.17.1", "indexmap", "log", - "object", + "object 0.40.0", "postcard", "rustc-demangle", "semver", @@ -3439,7 +3518,7 @@ dependencies = [ "gimli", "itertools", "log", - "object", + "object 0.40.0", "pulley-interpreter", "smallvec", "target-lexicon", @@ -3494,7 +3573,7 @@ checksum = "a0896123c430d063ba957dbe4c937740d3368c4877ecb208990d8f214cf1c4a9" dependencies = [ "cranelift-codegen", "log", - "object", + "object 0.40.0", "wasmtime-environ", ] diff --git a/Cargo.toml b/Cargo.toml index c4a4f3b4..e95d1a46 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,6 +17,7 @@ codeint-lang-go = { path = "plugins/languages/go" } codeint-lang-php = { path = "plugins/languages/php" } codeint-lang-python = { path = "plugins/languages/python" } codeint-lang-rust = { path = "plugins/languages/rust" } +codeint-lang-sql = { path = "plugins/languages/sql" } codeint-lang-ts = { path = "plugins/languages/ts" } codeint-metrics = { path = "crates/metrics" } codeint-model = { path = "crates/model" } @@ -37,6 +38,7 @@ schemars = "=1.2.3" serde = { version = "=1.0.229", features = ["derive"] } serde-saphyr = { version = "=2.1.1", default-features = false, features = ["deserialize"] } serde_json = "=1.0.154" +sqlparser = "=0.64.0" syn = { version = "=2.0.119", features = ["full", "visit"] } tempfile = "=3.27.0" thiserror = "=2.0.21" diff --git a/plugins/languages/sql/Cargo.toml b/plugins/languages/sql/Cargo.toml new file mode 100644 index 00000000..39868e0d --- /dev/null +++ b/plugins/languages/sql/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "codeint-lang-sql" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true + +[lints] +workspace = true + +[dependencies] +codeint-model = { workspace = true } +sqlparser = { workspace = true } diff --git a/plugins/languages/sql/src/flagged.rs b/plugins/languages/sql/src/flagged.rs new file mode 100644 index 00000000..0079b5d1 --- /dev/null +++ b/plugins/languages/sql/src/flagged.rs @@ -0,0 +1,715 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use codeint_model::language::FlaggedLine; +use codeint_model::scan::{finalize_flagged, flag_range}; +use sqlparser::ast::{ + BinaryOperator, DuplicateTreatment, Expr, Function, FunctionArg, FunctionArgExpr, + FunctionArguments, Ident, InTarget, JoinConstraint, JoinOperator, MacroDefinition, Query, + Select, SelectItem, SetExpr, Spanned, Statement, TableFactor, TableWithJoins, UnaryOperator, + Value, +}; +use sqlparser::keywords::Keyword; +use sqlparser::tokenizer::{Location, Token, TokenWithSpan}; + +use crate::ParsedSqlStatement; + +const RULES: &[&str] = &["or-chain-collapses-to-in", "having-without-aggregate"]; + +const AGGREGATE_FUNCTIONS: &[&str] = &[ + "any", + "any_value", + "approx_count_distinct", + "approx_quantile", + "arg_max", + "arg_min", + "argmax", + "argmin", + "array_agg", + "avg", + "bit_and", + "bit_or", + "bit_xor", + "bitstring_agg", + "bool_and", + "bool_or", + "corr", + "count", + "count_if", + "covar_pop", + "covar_samp", + "entropy", + "every", + "favg", + "first", + "fsum", + "group_concat", + "grouping", + "histogram", + "json_agg", + "json_arrayagg", + "json_group_array", + "json_group_object", + "json_object_agg", + "json_objectagg", + "jsonb_agg", + "jsonb_object_agg", + "kahan_sum", + "kurtosis", + "last", + "list", + "mad", + "max", + "median", + "min", + "mode", + "percentile_cont", + "percentile_disc", + "product", + "quantile", + "quantile_cont", + "quantile_disc", + "range_agg", + "range_intersect_agg", + "regr_avgx", + "regr_avgy", + "regr_count", + "regr_intercept", + "regr_r2", + "regr_slope", + "regr_sxx", + "regr_sxy", + "regr_syy", + "reservoir_quantile", + "skewness", + "some", + "std", + "stddev", + "stddev_pop", + "stddev_samp", + "string_agg", + "sum", + "sum_if", + "total", + "var_pop", + "var_samp", + "variance", + "xmlagg", +]; + +pub fn flagged_line_rules() -> impl Iterator { + RULES.iter().copied() +} + +pub(crate) fn evaluate( + parsed: &[ParsedSqlStatement], + code_lines: &BTreeSet, +) -> Vec { + let mut hits = BTreeSet::new(); + for stmt in parsed { + let mut checker = StatementChecker { + tokens: &stmt.tokens, + stmt_start_line: stmt.start_line, + code_lines, + hits: &mut hits, + }; + checker.visit_statement(&stmt.statement); + } + finalize_flagged(hits) +} + +struct StatementChecker<'a> { + tokens: &'a [TokenWithSpan], + stmt_start_line: u32, + code_lines: &'a BTreeSet, + hits: &'a mut BTreeSet<(u32, &'static str)>, +} + +impl StatementChecker<'_> { + fn flag(&mut self, line: u32, rule: &'static str) { + let target = if line > 0 { line } else { self.stmt_start_line }; + flag_range(target, target, rule, self.code_lines, self.hits); + } + + fn visit_statement(&mut self, stmt: &Statement) { + match stmt { + Statement::Query(query) => self.visit_query(query), + Statement::Explain { statement, .. } => self.visit_statement(statement), + Statement::Insert(_) + | Statement::Update(_) + | Statement::Delete(_) + | Statement::Merge(_) => { + self.visit_dml_statement(stmt); + } + _ => self.visit_ddl_statement(stmt), + } + } + + fn visit_dml_statement(&mut self, stmt: &Statement) { + match stmt { + Statement::Insert(insert) => self.visit_opt_query(insert.source.as_deref()), + Statement::Update(update) => self.visit_update(update), + Statement::Delete(delete) => self.visit_opt_expr(delete.selection.as_ref()), + Statement::Merge(merge) => self.visit_merge(merge), + _ => {} + } + } + + fn visit_ddl_statement(&mut self, stmt: &Statement) { + match stmt { + Statement::CreateView(view) => self.visit_query(&view.query), + Statement::CreateTable(table) => self.visit_opt_query(table.query.as_deref()), + Statement::CreateIndex(index) => self.visit_opt_expr(index.predicate.as_ref()), + Statement::CreateMacro { definition, .. } => self.visit_macro_def(definition), + _ => {} + } + } + + fn visit_opt_query(&mut self, query: Option<&Query>) { + if let Some(q) = query { + self.visit_query(q); + } + } + + fn visit_opt_expr(&mut self, expr: Option<&Expr>) { + if let Some(e) = expr { + self.visit_expr(e); + } + } + + fn visit_update(&mut self, update: &sqlparser::ast::Update) { + self.visit_table_with_joins(&update.table); + for assign in &update.assignments { + self.visit_expr(&assign.value); + } + self.visit_opt_expr(update.selection.as_ref()); + } + + fn visit_merge(&mut self, merge: &sqlparser::ast::Merge) { + self.visit_expr(&merge.on); + for clause in &merge.clauses { + self.visit_opt_expr(clause.predicate.as_ref()); + } + } + + fn visit_macro_def(&mut self, definition: &MacroDefinition) { + match definition { + MacroDefinition::Expr(expr) => self.visit_expr(expr), + MacroDefinition::Table(query) => self.visit_query(query), + } + } + + fn visit_query(&mut self, query: &Query) { + if let Some(with) = &query.with { + for cte in &with.cte_tables { + self.visit_query(&cte.query); + } + } + self.visit_set_expr(&query.body); + } + + fn visit_set_expr(&mut self, set_expr: &SetExpr) { + match set_expr { + SetExpr::Select(select) => self.visit_select(select), + SetExpr::Query(query) => self.visit_query(query), + SetExpr::SetOperation { left, right, .. } => { + self.visit_set_expr(left); + self.visit_set_expr(right); + } + SetExpr::Insert(stmt) + | SetExpr::Update(stmt) + | SetExpr::Delete(stmt) + | SetExpr::Merge(stmt) => self.visit_statement(stmt), + _ => {} + } + } + + fn visit_select(&mut self, select: &Select) { + for item in &select.projection { + self.visit_select_item(item); + } + for table in &select.from { + self.visit_table_with_joins(table); + } + if let Some(prewhere) = &select.prewhere { + self.visit_expr(prewhere); + } + if let Some(selection) = &select.selection { + self.visit_expr(selection); + } + if let Some(having) = &select.having { + self.check_having_without_aggregate(having); + self.visit_expr(having); + } + if let Some(qualify) = &select.qualify { + self.visit_expr(qualify); + } + } + + fn visit_select_item(&mut self, item: &SelectItem) { + match item { + SelectItem::UnnamedExpr(expr) + | SelectItem::ExprWithAlias { expr, .. } + | SelectItem::ExprWithAliases { expr, .. } => self.visit_expr(expr), + SelectItem::QualifiedWildcard(_, _) | SelectItem::Wildcard(_) => {} + } + } + + fn visit_table_with_joins(&mut self, table: &TableWithJoins) { + self.visit_table_factor(&table.relation); + for join in &table.joins { + self.visit_table_factor(&join.relation); + self.visit_join_operator(&join.join_operator); + } + } + + fn visit_table_factor(&mut self, factor: &TableFactor) { + match factor { + TableFactor::Derived { subquery, .. } => self.visit_query(subquery), + TableFactor::NestedJoin { + table_with_joins, .. + } => self.visit_table_with_joins(table_with_joins), + _ => {} + } + } + + fn visit_join_operator(&mut self, op: &JoinOperator) { + match op { + JoinOperator::Join(c) + | JoinOperator::Inner(c) + | JoinOperator::Left(c) + | JoinOperator::LeftOuter(c) + | JoinOperator::Right(c) + | JoinOperator::RightOuter(c) + | JoinOperator::FullOuter(c) + | JoinOperator::CrossJoin(c) + | JoinOperator::Semi(c) + | JoinOperator::LeftSemi(c) + | JoinOperator::RightSemi(c) + | JoinOperator::Anti(c) + | JoinOperator::LeftAnti(c) + | JoinOperator::RightAnti(c) => self.visit_join_constraint(c), + JoinOperator::AsOf { + match_condition, + constraint, + } => { + self.visit_expr(match_condition); + self.visit_join_constraint(constraint); + } + _ => {} + } + } + + fn visit_join_constraint(&mut self, constraint: &JoinConstraint) { + if let JoinConstraint::On(expr) = constraint { + self.visit_expr(expr); + } + } + + fn check_having_without_aggregate(&mut self, having: &Expr) { + if expr_contains_aggregate(having) { + return; + } + let line = find_having_line(self.tokens, having.span().start) + .unwrap_or(having.span().start.line as u32); + self.flag(line, "having-without-aggregate"); + } + + fn visit_expr(&mut self, expr: &Expr) { + if let Expr::BinaryOp { + op: BinaryOperator::Or, + .. + } = expr + { + self.inspect_or_chain(expr); + return; + } + self.visit_expr_children(expr); + } + + fn inspect_or_chain(&mut self, root: &Expr) { + let mut operands = Vec::new(); + flatten_or_operands(root, &mut operands); + + let mut counts: BTreeMap, (usize, u32)> = BTreeMap::new(); + for &operand in &operands { + if let Some((col_key, line)) = extract_column_eq_literal(operand) { + counts + .entry(col_key) + .and_modify(|(count, first_line)| { + *count += 1; + if line > 0 && (*first_line == 0 || line < *first_line) { + *first_line = line; + } + }) + .or_insert((1, line)); + } else { + self.visit_expr_children(operand); + } + } + + for (count, first_line) in counts.into_values() { + if count >= 3 { + self.flag(first_line, "or-chain-collapses-to-in"); + } + } + } + + fn visit_expr_children(&mut self, expr: &Expr) { + match expr { + Expr::BinaryOp { left, right, .. } + | Expr::IsDistinctFrom(left, right) + | Expr::IsNotDistinctFrom(left, right) + | Expr::AnyOp { left, right, .. } + | Expr::AllOp { left, right, .. } => { + self.visit_expr(left); + self.visit_expr(right); + } + Expr::UnaryOp { expr: inner, .. } + | Expr::Nested(inner) + | Expr::Cast { expr: inner, .. } + | Expr::IsNull(inner) + | Expr::IsNotNull(inner) + | Expr::IsTrue(inner) + | Expr::IsNotTrue(inner) + | Expr::IsFalse(inner) + | Expr::IsNotFalse(inner) => self.visit_expr(inner), + Expr::Between { + expr: target, + low, + high, + .. + } => { + self.visit_expr(target); + self.visit_expr(low); + self.visit_expr(high); + } + Expr::Case { + operand, + conditions, + else_result, + .. + } => self.visit_case(operand.as_deref(), conditions, else_result.as_deref()), + Expr::In { expr, target, .. } => { + self.visit_expr(expr); + self.visit_in_target(target); + } + Expr::Subquery(query) + | Expr::Exists { + subquery: query, .. + } => { + self.visit_query(query); + } + Expr::Function(func) => self.visit_function(func), + Expr::Tuple(items) => { + for item in items { + self.visit_expr(item); + } + } + _ => {} + } + } + + fn visit_case( + &mut self, + operand: Option<&Expr>, + conditions: &[sqlparser::ast::CaseWhen], + else_result: Option<&Expr>, + ) { + if let Some(op) = operand { + self.visit_expr(op); + } + for when in conditions { + self.visit_expr(&when.condition); + self.visit_expr(&when.result); + } + if let Some(els) = else_result { + self.visit_expr(els); + } + } + + fn visit_in_target(&mut self, target: &InTarget) { + match target { + InTarget::List(items) => { + for item in items { + self.visit_expr(item); + } + } + InTarget::Subquery(query) => self.visit_query(query), + InTarget::Unnest(expr) => self.visit_expr(expr), + InTarget::Table { .. } => {} + } + } + + fn visit_function(&mut self, func: &Function) { + if let Some(filter) = &func.filter { + self.visit_expr(filter); + } + match &func.args { + FunctionArguments::Subquery(query) => self.visit_query(query), + FunctionArguments::List(list) => { + for arg in &list.args { + if let Some(expr) = function_arg_expr(arg) { + self.visit_expr(expr); + } + } + } + FunctionArguments::None => {} + } + } +} + +fn flatten_or_operands<'a>(expr: &'a Expr, out: &mut Vec<&'a Expr>) { + let unwrapped = peel_nested(expr); + if let Expr::BinaryOp { + left, + op: BinaryOperator::Or, + right, + } = unwrapped + { + flatten_or_operands(left, out); + flatten_or_operands(right, out); + } else { + out.push(unwrapped); + } +} + +fn peel_nested(mut expr: &Expr) -> &Expr { + while let Expr::Nested(inner) = expr { + expr = inner; + } + expr +} + +fn extract_column_eq_literal(expr: &Expr) -> Option<(Vec, u32)> { + let Expr::BinaryOp { + left, + op: BinaryOperator::Eq, + right, + } = peel_nested(expr) + else { + return None; + }; + let line = expr.span().start.line as u32; + if let Some(col) = extract_column_key(left) + && is_constant_literal(right) + { + return Some((col, line)); + } + if let Some(col) = extract_column_key(right) + && is_constant_literal(left) + { + return Some((col, line)); + } + None +} + +fn extract_column_key(expr: &Expr) -> Option> { + match peel_nested(expr) { + Expr::Identifier(ident) => Some(vec![normalize_ident(ident)]), + Expr::CompoundIdentifier(idents) if !idents.is_empty() => { + Some(idents.iter().map(normalize_ident).collect()) + } + _ => None, + } +} + +fn normalize_ident(ident: &Ident) -> String { + if ident.quote_style.is_none() { + ident.value.to_ascii_lowercase() + } else { + ident.value.clone() + } +} + +fn is_constant_literal(expr: &Expr) -> bool { + match peel_nested(expr) { + Expr::Value(val) => !matches!(val.value, Value::Null | Value::Placeholder(_)), + Expr::TypedString(_) => true, + Expr::UnaryOp { + op: UnaryOperator::Plus | UnaryOperator::Minus, + expr: inner, + } => matches!( + peel_nested(inner), + Expr::Value(val) if matches!(val.value, Value::Number(_, _)) + ), + _ => false, + } +} + +fn expr_contains_aggregate(expr: &Expr) -> bool { + if let Some(inner) = unwrap_single_child_expr(expr) { + return expr_contains_aggregate(inner); + } + if let Some((left, right)) = unwrap_pair_expr(expr) { + return expr_contains_aggregate(left) || expr_contains_aggregate(right); + } + compound_expr_contains_aggregate(expr) +} + +fn unwrap_single_child_expr(expr: &Expr) -> Option<&Expr> { + match expr { + Expr::UnaryOp { expr: inner, .. } + | Expr::Nested(inner) + | Expr::Cast { expr: inner, .. } + | Expr::Convert { expr: inner, .. } + | Expr::Extract { expr: inner, .. } + | Expr::Ceil { expr: inner, .. } + | Expr::Floor { expr: inner, .. } + | Expr::Trim { expr: inner, .. } + | Expr::Collate { expr: inner, .. } + | Expr::IsNull(inner) + | Expr::IsNotNull(inner) + | Expr::IsTrue(inner) + | Expr::IsNotTrue(inner) + | Expr::IsFalse(inner) + | Expr::IsNotFalse(inner) + | Expr::IsUnknown(inner) + | Expr::IsNotUnknown(inner) => Some(inner), + _ => None, + } +} + +fn unwrap_pair_expr(expr: &Expr) -> Option<(&Expr, &Expr)> { + match expr { + Expr::BinaryOp { left, right, .. } + | Expr::IsDistinctFrom(left, right) + | Expr::IsNotDistinctFrom(left, right) + | Expr::Like { + expr: left, + pattern: right, + .. + } + | Expr::ILike { + expr: left, + pattern: right, + .. + } + | Expr::AnyOp { left, right, .. } + | Expr::AllOp { left, right, .. } => Some((left, right)), + _ => None, + } +} + +fn compound_expr_contains_aggregate(expr: &Expr) -> bool { + match expr { + Expr::Function(func) => is_aggregate_call(func) || function_args_contain_aggregate(func), + Expr::Between { + expr: target, + low, + high, + .. + } => between_contains_aggregate(target, low, high), + Expr::In { expr, target, .. } => { + expr_contains_aggregate(expr) || in_target_contains_aggregate(target) + } + Expr::Case { + operand, + conditions, + else_result, + .. + } => case_contains_aggregate(operand.as_deref(), conditions, else_result.as_deref()), + Expr::Tuple(items) => items.iter().any(expr_contains_aggregate), + Expr::Substring { + expr: inner, + substring_from, + substring_for, + .. + } => { + substring_contains_aggregate(inner, substring_from.as_deref(), substring_for.as_deref()) + } + _ => false, + } +} + +fn between_contains_aggregate(target: &Expr, low: &Expr, high: &Expr) -> bool { + expr_contains_aggregate(target) || expr_contains_aggregate(low) || expr_contains_aggregate(high) +} + +fn substring_contains_aggregate(inner: &Expr, from: Option<&Expr>, for_len: Option<&Expr>) -> bool { + expr_contains_aggregate(inner) + || from.is_some_and(expr_contains_aggregate) + || for_len.is_some_and(expr_contains_aggregate) +} + +fn case_contains_aggregate( + operand: Option<&Expr>, + conditions: &[sqlparser::ast::CaseWhen], + else_result: Option<&Expr>, +) -> bool { + operand.is_some_and(expr_contains_aggregate) + || conditions + .iter() + .any(|w| expr_contains_aggregate(&w.condition) || expr_contains_aggregate(&w.result)) + || else_result.is_some_and(expr_contains_aggregate) +} + +fn in_target_contains_aggregate(target: &InTarget) -> bool { + match target { + InTarget::List(items) => items.iter().any(expr_contains_aggregate), + InTarget::Unnest(expr) => expr_contains_aggregate(expr), + InTarget::Subquery(_) | InTarget::Table { .. } => false, + } +} + +fn is_aggregate_call(func: &Function) -> bool { + if func.over.is_some() { + return false; + } + if func.filter.is_some() || !func.within_group.is_empty() { + return true; + } + if let FunctionArguments::List(list) = &func.args + && list.duplicate_treatment == Some(DuplicateTreatment::Distinct) + { + return true; + } + let Some(last_ident) = func.name.0.last().and_then(|part| part.as_ident()) else { + return false; + }; + let lower = last_ident.value.to_ascii_lowercase(); + AGGREGATE_FUNCTIONS.binary_search(&lower.as_str()).is_ok() +} + +fn function_args_contain_aggregate(func: &Function) -> bool { + let FunctionArguments::List(list) = &func.args else { + return false; + }; + list.args + .iter() + .filter_map(function_arg_expr) + .any(expr_contains_aggregate) +} + +fn function_arg_expr(arg: &FunctionArg) -> Option<&Expr> { + let arg_expr = match arg { + FunctionArg::Unnamed(expr) + | FunctionArg::Named { arg: expr, .. } + | FunctionArg::ExprNamed { arg: expr, .. } => expr, + }; + match arg_expr { + FunctionArgExpr::Expr(expr) => Some(expr), + _ => None, + } +} + +fn find_having_line(tokens: &[TokenWithSpan], expr_start: Location) -> Option { + if expr_start.line == 0 { + return tokens + .iter() + .find(|t| matches!(&t.token, Token::Word(w) if w.keyword == Keyword::HAVING)) + .map(|t| t.span.start.line as u32); + } + let before = tokens + .iter() + .rposition(|t| t.span.start < expr_start && !matches!(t.token, Token::Whitespace(_)))?; + for tok in tokens[..=before].iter().rev() { + if matches!(tok.token, Token::Whitespace(_) | Token::LParen) { + continue; + } + if matches!(&tok.token, Token::Word(w) if w.keyword == Keyword::HAVING) { + return Some(tok.span.start.line as u32); + } + break; + } + None +} diff --git a/plugins/languages/sql/src/lib.rs b/plugins/languages/sql/src/lib.rs new file mode 100644 index 00000000..9a000aa6 --- /dev/null +++ b/plugins/languages/sql/src/lib.rs @@ -0,0 +1,255 @@ +#![forbid(unsafe_code)] + +mod flagged; +mod parser; +mod source_set; +mod statements; +mod tokenize; + +use std::collections::BTreeSet; +use std::fmt; + +use codeint_model::language::{ + DeclaredDep, FileModel, Function, ImportRequest, Manifest, Resolution, +}; +use codeint_model::{ + InvalidReferenceRange, LanguagePlugin, LanguagePluginError, LowerError, ReferenceRanges, + RepoPath, Token, WorkspaceError, +}; + +pub use flagged::flagged_line_rules; +pub use parser::{ParsedSqlStatement, RejectedSqlStatement}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum SqlDialect { + #[default] + Generic, + Postgresql, + Mysql, + Sqlite, + Duckdb, +} + +impl SqlDialect { + const fn labels(self) -> (&'static str, &'static str) { + match self { + SqlDialect::Generic => ("generic", "generic SQL"), + SqlDialect::Postgresql => ("postgresql", "postgresql"), + SqlDialect::Mysql => ("mysql", "mysql"), + SqlDialect::Sqlite => ("sqlite", "sqlite"), + SqlDialect::Duckdb => ("duckdb", "duckdb"), + } + } + + pub fn as_str(self) -> &'static str { + self.labels().0 + } + + pub fn display_name(self) -> &'static str { + self.labels().1 + } +} + +impl fmt::Display for SqlDialect { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(self.display_name()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SqlLowerOutput { + pub file_model: FileModel, + pub rejected_statements: Vec, + pub parsed_statements: Vec, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Sql { + dialect: SqlDialect, +} + +impl Sql { + pub fn new() -> Sql { + Sql { + dialect: SqlDialect::Generic, + } + } + + pub fn with_dialect(dialect: SqlDialect) -> Sql { + Sql { dialect } + } + + pub fn dialect(&self) -> SqlDialect { + self.dialect + } + + pub fn name(&self) -> &'static str { + "sql" + } + + pub fn lower_with_details( + &self, + path: &RepoPath, + source: &str, + ) -> Result { + if path.extension() != Some("sql") { + return Err(LowerError::UnsupportedFile { + message: format!("{} is not a SQL source file", path.as_str()), + }); + } + if source_set::has_template_markers(source, self.dialect) { + return Err(LowerError::Unparsable { + message: "templated SQL".to_owned(), + }); + } + + let tokenized = tokenize::tokenize_source(source, self.dialect)?; + let extracted = statements::extract_statements(&tokenized.chunks); + let (code_lines, duplication_tokens) = + collect_lines_and_tokens(&extracted, &tokenized.command_lines); + let source_lines = u32::try_from(code_lines.len()).map_err(|_| LowerError::TooLarge)?; + + let functions = build_functions(&extracted, &code_lines); + let (parsed_statements, rejected_statements) = + parse_all_statements(path, self.dialect, extracted); + let flagged_lines = flagged::evaluate(&parsed_statements, &code_lines); + let source_set = source_set::classify(path, source); + + Ok(SqlLowerOutput { + file_model: FileModel { + runtime_imports: Vec::new(), + flagged_lines, + hazard_lines: Vec::new(), + tokens: duplication_tokens, + functions, + source_lines, + source_set, + program_start: false, + }, + rejected_statements, + parsed_statements, + }) + } +} + +impl LanguagePlugin for Sql { + fn extensions(&self) -> Vec { + vec!["sql".to_owned()] + } + + fn lower(&self, path: &RepoPath, text: &str) -> Result { + self.lower_with_details(path, text) + .map(|output| output.file_model) + } + + fn manifest_paths(&self, _repository_paths: &[RepoPath]) -> Vec { + Vec::new() + } + + fn workspace_packages( + &self, + _manifests: Vec, + ) -> Result, WorkspaceError> { + Ok(Vec::new()) + } + + fn resolve_imports( + &self, + _repository_paths: &[RepoPath], + _manifests: Vec, + _requests: Vec, + ) -> Result, LanguagePluginError> { + Ok(Vec::new()) + } + + fn declared_dependencies( + &self, + _manifests: Vec, + ) -> Result, LanguagePluginError> { + Ok(Vec::new()) + } + + fn entry_points( + &self, + _repository_paths: &[RepoPath], + _manifests: Vec, + ) -> Result, LanguagePluginError> { + Ok(Vec::new()) + } + + fn reference_ranges(&self) -> Result { + Ok(ReferenceRanges::default()) + } + + fn has_hazard_rules(&self) -> bool { + false + } + + fn hazard_rules(&self) -> Vec { + Vec::new() + } + + fn has_imports(&self) -> bool { + false + } +} + +fn collect_lines_and_tokens( + extracted: &[statements::ExtractedStatement], + command_lines: &BTreeSet, +) -> (BTreeSet, Vec) { + let mut code_lines = command_lines.clone(); + let mut tokens = Vec::new(); + for stmt in extracted { + tokenize::collect_statement_lines_and_tokens( + &stmt.tokens, + &stmt.routine_body_tokens, + &mut code_lines, + &mut tokens, + ); + } + (code_lines, tokens) +} + +fn build_functions( + extracted: &[statements::ExtractedStatement], + code_lines: &BTreeSet, +) -> Vec { + extracted + .iter() + .map(|stmt| Function { + line: stmt.start_line, + end_line: stmt.end_line, + decision_points: stmt.decision_points, + source_lines: code_lines.range(stmt.start_line..=stmt.end_line).count() as u32, + name: stmt.name.clone(), + cognitive_complexity: stmt.cognitive_complexity, + coverage: None, + }) + .collect() +} + +fn parse_all_statements( + path: &RepoPath, + dialect: SqlDialect, + extracted: Vec, +) -> (Vec, Vec) { + let mut parsed = Vec::new(); + let mut rejected = Vec::new(); + for stmt in extracted { + match parser::parse_single_statement(dialect, stmt.tokens.clone()) { + Some(statement) => parsed.push(ParsedSqlStatement { + start_line: stmt.start_line, + end_line: stmt.end_line, + statement, + tokens: stmt.tokens, + }), + None => rejected.push(RejectedSqlStatement { + path: path.clone(), + line: stmt.start_line, + dialect, + }), + } + } + (parsed, rejected) +} diff --git a/plugins/languages/sql/src/parser.rs b/plugins/languages/sql/src/parser.rs new file mode 100644 index 00000000..e6671f4e --- /dev/null +++ b/plugins/languages/sql/src/parser.rs @@ -0,0 +1,35 @@ +use codeint_model::RepoPath; +use sqlparser::ast::Statement; +use sqlparser::parser::Parser; +use sqlparser::tokenizer::TokenWithSpan; + +use crate::SqlDialect; +use crate::tokenize::sqlparser_dialect; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RejectedSqlStatement { + pub path: RepoPath, + pub line: u32, + pub dialect: SqlDialect, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ParsedSqlStatement { + pub start_line: u32, + pub end_line: u32, + pub statement: Statement, + pub tokens: Vec, +} + +pub(crate) fn parse_single_statement( + dialect: SqlDialect, + tokens: Vec, +) -> Option { + let mut parser = Parser::new(sqlparser_dialect(dialect)).with_tokens_with_locations(tokens); + let mut statements = parser.parse_statements().ok()?; + if statements.len() == 1 { + statements.pop() + } else { + None + } +} diff --git a/plugins/languages/sql/src/source_set.rs b/plugins/languages/sql/src/source_set.rs new file mode 100644 index 00000000..9859bb63 --- /dev/null +++ b/plugins/languages/sql/src/source_set.rs @@ -0,0 +1,231 @@ +use codeint_model::{RepoPath, SourceSet}; + +use crate::SqlDialect; + +const DUMP_HEADER_LINES: usize = 20; + +const DUMP_HEADER_PREFIXES: &[&str] = &[ + "-- PostgreSQL database dump", + "-- Dumped by pg_dump", + "-- MySQL dump ", + "-- MariaDB database dump", + "-- MariaDB dump ", +]; + +const MIGRATION_MARKER_PREFIXES: &[&str] = &[ + "--> statement-breakpoint", + "-- atlas:txmode", + "-- atlas:nolint", +]; + +const TEST_FOLDER_NAMES: &[&str] = &["test", "tests", "fixtures"]; + +pub(crate) fn classify(path: &RepoPath, source: &str) -> SourceSet { + if has_dump_header(source) + || has_migration_marker(source) + || is_generated_migration_folder(path) + { + return SourceSet::Generated; + } + if is_test_folder(path) { + return SourceSet::Test; + } + SourceSet::Production +} + +fn has_dump_header(source: &str) -> bool { + let text = source.strip_prefix('\u{feff}').unwrap_or(source); + text.lines().take(DUMP_HEADER_LINES).any(|line| { + let trimmed = line.trim_start(); + DUMP_HEADER_PREFIXES + .iter() + .any(|prefix| trimmed.starts_with(prefix)) + }) +} + +fn has_migration_marker(source: &str) -> bool { + let text = source.strip_prefix('\u{feff}').unwrap_or(source); + text.lines().any(|line| { + let trimmed = line.trim_start(); + MIGRATION_MARKER_PREFIXES + .iter() + .any(|prefix| trimmed.starts_with(prefix)) + }) +} + +fn is_generated_migration_folder(path: &RepoPath) -> bool { + let Some((parent, _)) = path.as_str().rsplit_once('/') else { + return false; + }; + let segments: Vec<&str> = parent.split('/').collect(); + let has_drizzle = segments.contains(&"drizzle"); + let has_prisma_migrations = segments + .windows(2) + .any(|pair| pair == ["prisma", "migrations"]); + has_drizzle || has_prisma_migrations +} + +fn is_test_folder(path: &RepoPath) -> bool { + let Some((parent, _)) = path.as_str().rsplit_once('/') else { + return false; + }; + parent + .split('/') + .any(|segment| TEST_FOLDER_NAMES.contains(&segment)) +} + +pub(crate) fn has_template_markers(source: &str, dialect: SqlDialect) -> bool { + let bytes = source.as_bytes(); + let nested_comments = matches!( + dialect, + SqlDialect::Generic | SqlDialect::Postgresql | SqlDialect::Duckdb + ); + let mysql_mode = dialect == SqlDialect::Mysql; + let mut pos = 0usize; + + while pos < bytes.len() { + if let Some(next) = skip_comment_or_string(bytes, pos, nested_comments, mysql_mode) { + pos = next; + continue; + } + if is_template_marker_at(bytes, pos) { + return true; + } + pos += 1; + } + false +} + +fn is_template_marker_at(bytes: &[u8], pos: usize) -> bool { + if pos + 1 >= bytes.len() { + return false; + } + matches!(&bytes[pos..pos + 2], b"{{" | b"{%" | b"%}" | b"<%" | b"%>") +} + +fn skip_comment_or_string( + bytes: &[u8], + pos: usize, + nested_comments: bool, + mysql_mode: bool, +) -> Option { + skip_comment(bytes, pos, nested_comments, mysql_mode) + .or_else(|| skip_quoted_or_dollar(bytes, pos, mysql_mode)) +} + +fn skip_comment( + bytes: &[u8], + pos: usize, + nested_comments: bool, + mysql_mode: bool, +) -> Option { + let ch = bytes[pos]; + if ch == b'-' && bytes.get(pos + 1) == Some(&b'-') { + return Some(skip_to_line_end(bytes, pos + 2)); + } + if mysql_mode && ch == b'#' { + return Some(skip_to_line_end(bytes, pos + 1)); + } + if ch == b'/' && bytes.get(pos + 1) == Some(&b'*') { + return Some(skip_block_comment(bytes, pos + 2, nested_comments)); + } + None +} + +fn skip_quoted_or_dollar(bytes: &[u8], pos: usize, mysql_mode: bool) -> Option { + match bytes[pos] { + b'\'' => { + let backslash = mysql_mode || is_pg_escaped_prefix(bytes, pos); + Some(skip_quoted(bytes, pos + 1, b'\'', backslash)) + } + b'"' => Some(skip_quoted(bytes, pos + 1, b'"', mysql_mode)), + b'`' => Some(skip_quoted(bytes, pos + 1, b'`', false)), + b'$' => skip_dollar_quoted(bytes, pos), + _ => None, + } +} + +fn is_pg_escaped_prefix(bytes: &[u8], quote_pos: usize) -> bool { + if quote_pos == 0 || !matches!(bytes[quote_pos - 1], b'e' | b'E') { + return false; + } + quote_pos == 1 || !is_ident_byte(bytes[quote_pos - 2]) +} + +fn is_ident_byte(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || byte == b'_' +} + +fn skip_to_line_end(bytes: &[u8], mut pos: usize) -> usize { + while pos < bytes.len() && bytes[pos] != b'\n' { + pos += 1; + } + pos +} + +fn skip_block_comment(bytes: &[u8], mut pos: usize, nested: bool) -> usize { + let mut depth = 1usize; + while pos + 1 < bytes.len() { + if nested && bytes[pos] == b'/' && bytes[pos + 1] == b'*' { + depth += 1; + pos += 2; + } else if bytes[pos] == b'*' && bytes[pos + 1] == b'/' { + depth -= 1; + pos += 2; + if depth == 0 { + return pos; + } + } else { + pos += 1; + } + } + bytes.len() +} + +fn skip_quoted(bytes: &[u8], mut pos: usize, quote: u8, backslash_escape: bool) -> usize { + while pos < bytes.len() { + let ch = bytes[pos]; + if backslash_escape && ch == b'\\' && pos + 1 < bytes.len() { + pos += 2; + } else if ch == quote { + if bytes.get(pos + 1) == Some("e) { + pos += 2; + } else { + return pos + 1; + } + } else { + pos += 1; + } + } + bytes.len() +} + +pub(crate) fn parse_dollar_tag(bytes: &[u8], start: usize) -> Option<&[u8]> { + if bytes.get(start) != Some(&b'$') { + return None; + } + if bytes.get(start + 1) == Some(&b'$') { + return Some(&bytes[start..start + 2]); + } + let first = *bytes.get(start + 1)?; + if !(first.is_ascii_alphabetic() || first == b'_') { + return None; + } + let mut pos = start + 2; + while pos < bytes.len() && is_ident_byte(bytes[pos]) { + pos += 1; + } + (bytes.get(pos) == Some(&b'$')).then_some(&bytes[start..=pos]) +} + +fn skip_dollar_quoted(bytes: &[u8], start: usize) -> Option { + let tag = parse_dollar_tag(bytes, start)?; + let mut pos = start + tag.len(); + while pos + tag.len() <= bytes.len() { + if &bytes[pos..pos + tag.len()] == tag { + return Some(pos + tag.len()); + } + pos += 1; + } + Some(bytes.len()) +} diff --git a/plugins/languages/sql/src/statements.rs b/plugins/languages/sql/src/statements.rs new file mode 100644 index 00000000..d00d6971 --- /dev/null +++ b/plugins/languages/sql/src/statements.rs @@ -0,0 +1,879 @@ +use sqlparser::tokenizer::{Token, TokenWithSpan}; + +use crate::tokenize::{TokenChunk, tokenize_pg_routine_body}; + +pub(crate) struct ExtractedStatement { + pub(crate) start_line: u32, + pub(crate) end_line: u32, + pub(crate) name: Option, + pub(crate) decision_points: u32, + pub(crate) cognitive_complexity: u32, + pub(crate) tokens: Vec, + pub(crate) routine_body_tokens: Vec>, +} + +pub(crate) fn extract_statements(chunks: &[TokenChunk]) -> Vec { + let mut statements = Vec::new(); + for chunk in chunks { + if chunk.is_custom_delimited { + if let Some(stmt) = finalize_statement(chunk.tokens.clone()) { + statements.push(stmt); + } + } else { + for raw_tokens in split_standard_chunk(&chunk.tokens) { + if let Some(stmt) = finalize_statement(raw_tokens) { + statements.push(stmt); + } + } + } + } + statements +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum SplitBlock { + Begin, + Case, +} + +struct SplitState { + paren_depth: usize, + blocks: Vec, + is_routine_stmt: bool, + stmt_start: usize, +} + +fn split_standard_chunk(tokens: &[TokenWithSpan]) -> Vec> { + let mut result = Vec::new(); + let mut state = SplitState { + paren_depth: 0, + blocks: Vec::new(), + is_routine_stmt: false, + stmt_start: 0, + }; + let mut idx = 0usize; + + while idx < tokens.len() { + idx = step_split_token(tokens, idx, &mut state, &mut result); + } + push_trimmed_slice(tokens, state.stmt_start, tokens.len(), &mut result); + result +} + +fn step_split_token( + tokens: &[TokenWithSpan], + idx: usize, + state: &mut SplitState, + result: &mut Vec>, +) -> usize { + let tok = &tokens[idx].token; + if matches!(tok, Token::Whitespace(_) | Token::EOF) { + return idx + 1; + } + detect_routine_start(tokens, idx, state); + match tok { + Token::LParen => state.paren_depth += 1, + Token::RParen => state.paren_depth = state.paren_depth.saturating_sub(1), + Token::SemiColon if state.paren_depth == 0 && state.blocks.is_empty() => { + finish_top_level_stmt(tokens, idx, state, result); + } + Token::Word(_) if state.is_routine_stmt => { + return update_routine_split_blocks(tokens, idx, &mut state.blocks); + } + _ => {} + } + idx + 1 +} + +fn detect_routine_start(tokens: &[TokenWithSpan], idx: usize, state: &mut SplitState) { + if state.stmt_start <= idx && !has_code_before(tokens, state.stmt_start, idx) { + state.is_routine_stmt = starts_routine_header(tokens, idx); + } +} + +fn finish_top_level_stmt( + tokens: &[TokenWithSpan], + idx: usize, + state: &mut SplitState, + result: &mut Vec>, +) { + push_trimmed_slice(tokens, state.stmt_start, idx, result); + state.stmt_start = idx + 1; + state.is_routine_stmt = false; +} + +fn has_code_before(tokens: &[TokenWithSpan], start: usize, end: usize) -> bool { + tokens[start..end] + .iter() + .any(|t| !matches!(t.token, Token::Whitespace(_) | Token::EOF)) +} + +fn starts_routine_header(tokens: &[TokenWithSpan], start: usize) -> bool { + if !is_unquoted_kw(&tokens[start], "CREATE") { + return false; + } + let mut pos = start; + while let Some(next) = next_code_idx(tokens, pos + 1) { + let tok = &tokens[next]; + if is_unquoted_kw(tok, "TRIGGER") + || is_unquoted_kw(tok, "PROCEDURE") + || is_unquoted_kw(tok, "FUNCTION") + { + return true; + } + if matches!(tok.token, Token::SemiColon | Token::LParen) { + return false; + } + pos = next; + } + false +} + +fn update_routine_split_blocks( + tokens: &[TokenWithSpan], + idx: usize, + blocks: &mut Vec, +) -> usize { + let tok = &tokens[idx]; + if is_unquoted_kw(tok, "BEGIN") { + blocks.push(SplitBlock::Begin); + return idx + 1; + } + if is_unquoted_kw(tok, "CASE") && !blocks.is_empty() { + blocks.push(SplitBlock::Case); + return idx + 1; + } + if is_unquoted_kw(tok, "END") && !blocks.is_empty() { + return handle_split_end(tokens, idx, blocks); + } + idx + 1 +} + +fn handle_split_end(tokens: &[TokenWithSpan], idx: usize, blocks: &mut Vec) -> usize { + if let Some(next) = next_code_idx(tokens, idx + 1) { + if is_unquoted_kw(&tokens[next], "CASE") { + pop_matching_split_block(blocks, SplitBlock::Case); + return next + 1; + } + if is_compound_end_tail(&tokens[next]) { + return next + 1; + } + } + blocks.pop(); + idx + 1 +} + +fn pop_matching_split_block(blocks: &mut Vec, target: SplitBlock) { + if let Some(pos) = blocks.iter().rposition(|&b| b == target) { + blocks.truncate(pos); + } +} + +fn is_compound_end_tail(tok: &TokenWithSpan) -> bool { + is_unquoted_kw(tok, "IF") + || is_unquoted_kw(tok, "LOOP") + || is_unquoted_kw(tok, "WHILE") + || is_unquoted_kw(tok, "REPEAT") +} + +fn push_trimmed_slice( + tokens: &[TokenWithSpan], + start: usize, + end: usize, + out: &mut Vec>, +) { + let slice = &tokens[start..end]; + let first = slice + .iter() + .position(|t| !matches!(t.token, Token::Whitespace(_) | Token::EOF)); + let last = slice + .iter() + .rposition(|t| !matches!(t.token, Token::Whitespace(_) | Token::EOF)); + if let (Some(first), Some(last)) = (first, last) { + out.push(slice[first..=last].to_vec()); + } +} + +fn finalize_statement(tokens: Vec) -> Option { + let code_tokens: Vec<&TokenWithSpan> = tokens + .iter() + .filter(|t| !matches!(t.token, Token::Whitespace(_) | Token::EOF)) + .collect(); + let first = *code_tokens.first()?; + let last = *code_tokens.last()?; + let start_line = first.span.start.line as u32; + let end_line = (last.span.end.line as u32).max(start_line); + let name = extract_object_name(&code_tokens); + let scored = score_statement(&code_tokens); + Some(ExtractedStatement { + start_line, + end_line, + name, + decision_points: scored.decision_points, + cognitive_complexity: scored.cognitive_complexity, + tokens, + routine_body_tokens: scored.routine_body_tokens, + }) +} + +fn extract_object_name(code: &[&TokenWithSpan]) -> Option { + if !code.first().is_some_and(|t| is_unquoted_kw(t, "CREATE")) { + return None; + } + let mut pos = skip_create_modifiers(code, 1); + let kind_tok = *code.get(pos)?; + if !is_named_object_kind(kind_tok) { + return None; + } + let is_index = is_unquoted_kw(kind_tok, "INDEX"); + pos += 1; + if is_index + && code + .get(pos) + .is_some_and(|t| is_unquoted_kw(t, "CONCURRENTLY")) + { + pos += 1; + } + pos = skip_if_not_exists(code, pos); + let first = *code.get(pos)?; + if is_index && is_unquoted_kw(first, "ON") { + return None; + } + read_qualified_name(code, pos) +} + +fn skip_create_modifiers(code: &[&TokenWithSpan], mut pos: usize) -> usize { + while pos < code.len() { + let tok = code[pos]; + if is_unquoted_kw(tok, "OR") + && code + .get(pos + 1) + .is_some_and(|t| is_unquoted_kw(t, "REPLACE")) + { + pos += 2; + } else if is_single_create_modifier(tok) { + pos += 1; + } else if is_unquoted_kw(tok, "DEFINER") { + pos = skip_definer_clause(code, pos + 1); + } else if is_unquoted_kw(tok, "ALGORITHM") { + pos = skip_key_eq_val(code, pos + 1); + } else if is_unquoted_kw(tok, "SQL") + && code + .get(pos + 1) + .is_some_and(|t| is_unquoted_kw(t, "SECURITY")) + { + pos = (pos + 3).min(code.len()); + } else { + break; + } + } + pos +} + +fn is_single_create_modifier(tok: &TokenWithSpan) -> bool { + let Some(word) = unquoted_word(tok) else { + return false; + }; + matches!( + word.to_ascii_uppercase().as_str(), + "TEMP" + | "TEMPORARY" + | "UNLOGGED" + | "MATERIALIZED" + | "UNIQUE" + | "RECURSIVE" + | "GLOBAL" + | "LOCAL" + | "FULLTEXT" + | "SPATIAL" + | "CONSTRAINT" + ) +} + +fn skip_key_eq_val(code: &[&TokenWithSpan], mut pos: usize) -> usize { + if code.get(pos).is_some_and(|t| t.token == Token::Eq) { + pos += 1; + } + (pos + 1).min(code.len()) +} + +fn skip_definer_clause(code: &[&TokenWithSpan], mut pos: usize) -> usize { + if code.get(pos).is_some_and(|t| t.token == Token::Eq) { + pos += 1; + } + while pos < code.len() { + let tok = code[pos]; + if is_named_object_kind(tok) + || is_unquoted_kw(tok, "SQL") + || is_unquoted_kw(tok, "ALGORITHM") + { + break; + } + pos += 1; + } + pos +} + +fn is_named_object_kind(tok: &TokenWithSpan) -> bool { + let Some(word) = unquoted_word(tok) else { + return false; + }; + matches!( + word.to_ascii_uppercase().as_str(), + "TABLE" | "VIEW" | "INDEX" | "FUNCTION" | "PROCEDURE" | "TRIGGER" | "TYPE" | "MACRO" + ) +} + +fn skip_if_not_exists(code: &[&TokenWithSpan], pos: usize) -> usize { + if code.get(pos).is_some_and(|t| is_unquoted_kw(t, "IF")) + && code.get(pos + 1).is_some_and(|t| is_unquoted_kw(t, "NOT")) + && code + .get(pos + 2) + .is_some_and(|t| is_unquoted_kw(t, "EXISTS")) + { + pos + 3 + } else { + pos + } +} + +fn read_qualified_name(code: &[&TokenWithSpan], mut pos: usize) -> Option { + let Token::Word(first) = &code.get(pos)?.token else { + return None; + }; + let mut name = first.value.clone(); + pos += 1; + while code.get(pos).is_some_and(|t| t.token == Token::Period) + && let Some(Token::Word(part)) = code.get(pos + 1).map(|t| &t.token) + { + name.push('.'); + name.push_str(&part.value); + pos += 2; + } + Some(name) +} + +struct StatementScore { + decision_points: u32, + cognitive_complexity: u32, + routine_body_tokens: Vec>, +} + +fn score_statement(code: &[&TokenWithSpan]) -> StatementScore { + let routine_kind = classify_routine_statement(code); + let mut scorer = ComplexityScorer::new(routine_kind.is_inline_routine()); + let mut routine_body_tokens = Vec::new(); + let mut idx = 0usize; + + while idx < code.len() { + if routine_kind.allows_dollar_body() + && is_routine_dollar_body(code, idx, routine_kind) + && let Token::DollarQuotedString(dq) = &code[idx].token + { + if let Some(inner) = + tokenize_pg_routine_body(&dq.value, code[idx].span.start.line as u32) + { + let inner_code: Vec<&TokenWithSpan> = inner + .iter() + .filter(|t| !matches!(t.token, Token::Whitespace(_) | Token::EOF)) + .collect(); + scorer.score_slice(&inner_code, true); + routine_body_tokens.push(inner); + } + idx += 1; + continue; + } + idx = scorer.step(code, idx); + } + + StatementScore { + decision_points: scorer.decision_points, + cognitive_complexity: scorer.cognitive_complexity, + routine_body_tokens, + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum RoutineKind { + None, + CreateRoutine, + PgDo, +} + +impl RoutineKind { + fn is_inline_routine(self) -> bool { + self == RoutineKind::CreateRoutine + } + + fn allows_dollar_body(self) -> bool { + self != RoutineKind::None + } +} + +fn classify_routine_statement(code: &[&TokenWithSpan]) -> RoutineKind { + let Some(first) = code.first() else { + return RoutineKind::None; + }; + if is_unquoted_kw(first, "DO") { + return RoutineKind::PgDo; + } + if !is_unquoted_kw(first, "CREATE") { + return RoutineKind::None; + } + let pos = skip_create_modifiers(code, 1); + let is_routine = code.get(pos).is_some_and(|t| { + is_unquoted_kw(t, "FUNCTION") + || is_unquoted_kw(t, "PROCEDURE") + || is_unquoted_kw(t, "TRIGGER") + }); + if is_routine { + RoutineKind::CreateRoutine + } else { + RoutineKind::None + } +} + +fn is_routine_dollar_body(code: &[&TokenWithSpan], idx: usize, kind: RoutineKind) -> bool { + if !matches!(code[idx].token, Token::DollarQuotedString(_)) { + return false; + } + if !has_sql_compatible_language(code) { + return false; + } + match kind { + RoutineKind::PgDo => true, + RoutineKind::CreateRoutine => idx > 0 && is_unquoted_kw(code[idx - 1], "AS"), + RoutineKind::None => false, + } +} + +fn has_sql_compatible_language(code: &[&TokenWithSpan]) -> bool { + let Some(lang_idx) = code.iter().position(|t| is_unquoted_kw(t, "LANGUAGE")) else { + return true; + }; + let Some(next) = code.get(lang_idx + 1) else { + return true; + }; + let lang = match &next.token { + Token::Word(w) => w.value.as_str(), + Token::SingleQuotedString(s) => s.as_str(), + _ => return true, + }; + lang.eq_ignore_ascii_case("sql") || lang.eq_ignore_ascii_case("plpgsql") +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum ActiveBlock { + Case, + Begin { has_exception: bool }, + If, + Loop, +} + +struct ComplexityScorer { + decision_points: u32, + cognitive_complexity: u32, + in_routine: bool, + paren_subquery_stack: Vec, + subquery_depth: u32, + routine_block_depth: u32, + blocks: Vec, + between_paren_depths: Vec, + expect_loop_keyword: bool, +} + +impl ComplexityScorer { + fn new(in_routine: bool) -> Self { + Self { + decision_points: 0, + cognitive_complexity: 0, + in_routine, + paren_subquery_stack: Vec::new(), + subquery_depth: 0, + routine_block_depth: 0, + blocks: Vec::new(), + between_paren_depths: Vec::new(), + expect_loop_keyword: false, + } + } + + fn score_slice(&mut self, code: &[&TokenWithSpan], in_routine: bool) { + let saved = self.in_routine; + self.in_routine = in_routine; + let mut idx = 0usize; + while idx < code.len() { + idx = self.step(code, idx); + } + self.in_routine = saved; + } + + fn depth(&self) -> u32 { + self.subquery_depth.saturating_add(self.routine_block_depth) + } + + fn add_decision(&mut self, depth: u32) { + self.decision_points = self.decision_points.saturating_add(1); + self.cognitive_complexity = self + .cognitive_complexity + .saturating_add(depth.saturating_add(1)); + } + + fn step(&mut self, code: &[&TokenWithSpan], idx: usize) -> usize { + let tok = code[idx]; + match &tok.token { + Token::LParen => { + self.handle_lparen(code, idx); + idx + 1 + } + Token::RParen => { + self.handle_rparen(); + idx + 1 + } + Token::Word(_) => self.handle_word(code, idx), + _ => idx + 1, + } + } + + fn handle_lparen(&mut self, code: &[&TokenWithSpan], idx: usize) { + let is_subquery = code + .get(idx + 1) + .is_some_and(|next| is_unquoted_kw(next, "SELECT") || is_unquoted_kw(next, "WITH")); + if is_subquery { + self.add_decision(self.depth()); + self.subquery_depth += 1; + } + self.paren_subquery_stack.push(is_subquery); + } + + fn handle_rparen(&mut self) { + let closing_depth = self.paren_subquery_stack.len(); + while self.between_paren_depths.last() == Some(&closing_depth) { + self.between_paren_depths.pop(); + } + if self.paren_subquery_stack.pop() == Some(true) { + self.subquery_depth = self.subquery_depth.saturating_sub(1); + } + } + + fn handle_word(&mut self, code: &[&TokenWithSpan], idx: usize) -> usize { + let Some(word) = unquoted_word(code[idx]) else { + return idx + 1; + }; + let upper = word.to_ascii_uppercase(); + if self.handle_query_keyword(code, idx, &upper) { + return idx + 1; + } + if self.in_routine { + return self.handle_routine_keyword(code, idx, &upper); + } + if upper == "END" { + self.pop_case_block(); + } + idx + 1 + } + + fn handle_query_keyword(&mut self, code: &[&TokenWithSpan], idx: usize, upper: &str) -> bool { + if self.handle_case_or_between(upper) { + return true; + } + match upper { + "AND" => self.handle_and_keyword(code, idx), + "OR" if !is_non_condition_or(code, idx) => self.add_decision(self.depth()), + "OR" => {} + "JOIN" | "STRAIGHT_JOIN" | "UNION" | "INTERSECT" => self.add_decision(self.depth()), + "EXCEPT" if !is_wildcard_except(code, idx) => self.add_decision(self.depth()), + "EXCEPT" => {} + _ => return false, + } + true + } + + fn handle_case_or_between(&mut self, upper: &str) -> bool { + match upper { + "CASE" => self.blocks.push(ActiveBlock::Case), + "WHEN" if self.blocks.last() == Some(&ActiveBlock::Case) => { + self.add_decision(self.depth()); + } + "WHEN" => {} + "BETWEEN" => self + .between_paren_depths + .push(self.paren_subquery_stack.len()), + _ => return false, + } + true + } + + fn handle_and_keyword(&mut self, code: &[&TokenWithSpan], idx: usize) { + let current_paren = self.paren_subquery_stack.len(); + if self.between_paren_depths.last() == Some(¤t_paren) { + self.between_paren_depths.pop(); + return; + } + if is_transaction_chain_and(code, idx) { + return; + } + self.add_decision(self.depth()); + } + + fn handle_routine_keyword( + &mut self, + code: &[&TokenWithSpan], + idx: usize, + upper: &str, + ) -> usize { + if upper == "END" { + return self.handle_routine_end(code, idx); + } + if !self.handle_routine_branch_keyword(code, idx, upper) { + self.handle_routine_loop_keyword(code, idx, upper); + } + idx + 1 + } + + fn handle_routine_branch_keyword( + &mut self, + code: &[&TokenWithSpan], + idx: usize, + upper: &str, + ) -> bool { + match upper { + "BEGIN" => self.blocks.push(ActiveBlock::Begin { + has_exception: false, + }), + "IF" => self.handle_routine_if(code, idx), + "ELSIF" | "ELSEIF" => { + let d = self.depth().saturating_sub(1); + self.add_decision(d); + } + "EXCEPTION" => self.handle_routine_exception(), + "HANDLER" => self.add_decision(self.depth()), + _ => return false, + } + true + } + + fn handle_routine_loop_keyword(&mut self, code: &[&TokenWithSpan], idx: usize, upper: &str) { + match upper { + "WHILE" => self.enter_loop_block(true), + "FOR" if is_routine_for_loop(code, idx, self.paren_subquery_stack.len()) => { + self.enter_loop_block(true); + } + "REPEAT" if !code.get(idx + 1).is_some_and(|t| t.token == Token::LParen) => { + self.enter_loop_block(false); + } + "LOOP" => self.handle_routine_loop(), + _ => {} + } + } + + fn handle_routine_if(&mut self, code: &[&TokenWithSpan], idx: usize) { + if is_ddl_if_guard(code, idx) || is_scalar_if_call(code, idx) { + return; + } + self.add_decision(self.depth()); + self.blocks.push(ActiveBlock::If); + self.routine_block_depth += 1; + } + + fn enter_loop_block(&mut self, expects_loop: bool) { + self.add_decision(self.depth()); + self.blocks.push(ActiveBlock::Loop); + self.routine_block_depth += 1; + self.expect_loop_keyword = expects_loop; + } + + fn handle_routine_loop(&mut self) { + if self.expect_loop_keyword { + self.expect_loop_keyword = false; + } else { + self.enter_loop_block(false); + } + } + + fn handle_routine_exception(&mut self) { + self.add_decision(self.depth()); + if let Some(ActiveBlock::Begin { has_exception }) = self + .blocks + .iter_mut() + .rev() + .find(|b| matches!(b, ActiveBlock::Begin { .. })) + && !*has_exception + { + *has_exception = true; + self.routine_block_depth += 1; + } + } + + fn handle_routine_end(&mut self, code: &[&TokenWithSpan], idx: usize) -> usize { + if let Some(next) = code.get(idx + 1) { + if is_unquoted_kw(next, "IF") { + self.pop_routine_block(ActiveBlock::If); + return idx + 2; + } + if is_unquoted_kw(next, "LOOP") + || is_unquoted_kw(next, "WHILE") + || is_unquoted_kw(next, "REPEAT") + { + self.pop_routine_block(ActiveBlock::Loop); + return idx + 2; + } + if is_unquoted_kw(next, "CASE") { + self.pop_case_block(); + return idx + 2; + } + } + match self.blocks.pop() { + Some(ActiveBlock::Begin { + has_exception: true, + }) => { + self.routine_block_depth = self.routine_block_depth.saturating_sub(1); + } + Some(ActiveBlock::If | ActiveBlock::Loop) => { + self.routine_block_depth = self.routine_block_depth.saturating_sub(1); + } + _ => {} + } + idx + 1 + } + + fn pop_routine_block(&mut self, target: ActiveBlock) { + if let Some(pos) = self.blocks.iter().rposition(|&b| b == target) { + self.blocks.remove(pos); + self.routine_block_depth = self.routine_block_depth.saturating_sub(1); + } + } + + fn pop_case_block(&mut self) { + if let Some(pos) = self.blocks.iter().rposition(|&b| b == ActiveBlock::Case) { + self.blocks.remove(pos); + } + } +} + +fn is_ddl_if_guard(code: &[&TokenWithSpan], idx: usize) -> bool { + let next_exists = code + .get(idx + 1) + .is_some_and(|t| is_unquoted_kw(t, "EXISTS")) + && !code.get(idx + 2).is_some_and(|t| t.token == Token::LParen); + let next_not_exists = code.get(idx + 1).is_some_and(|t| is_unquoted_kw(t, "NOT")) + && code + .get(idx + 2) + .is_some_and(|t| is_unquoted_kw(t, "EXISTS")) + && !code.get(idx + 3).is_some_and(|t| t.token == Token::LParen); + next_exists || next_not_exists +} + +fn is_scalar_if_call(code: &[&TokenWithSpan], idx: usize) -> bool { + if !code.get(idx + 1).is_some_and(|t| t.token == Token::LParen) { + return false; + } + let Some(close) = find_matching_rparen(code, idx + 1) else { + return false; + }; + !code + .get(close + 1) + .is_some_and(|t| is_unquoted_kw(t, "THEN")) +} + +fn find_matching_rparen(code: &[&TokenWithSpan], open: usize) -> Option { + let mut depth = 0usize; + for (idx, tok) in code.iter().enumerate().skip(open) { + match tok.token { + Token::LParen => depth += 1, + Token::RParen => { + depth -= 1; + if depth == 0 { + return Some(idx); + } + } + _ => {} + } + } + None +} + +fn is_routine_for_loop(code: &[&TokenWithSpan], idx: usize, paren_depth: usize) -> bool { + if paren_depth > 0 { + return false; + } + if idx > 0 && is_unquoted_kw(code[idx - 1], "HANDLER") { + return false; + } + let Some(next) = code.get(idx + 1) else { + return false; + }; + let excluded = is_unquoted_kw(next, "EACH") + || is_unquoted_kw(next, "UPDATE") + || is_unquoted_kw(next, "SHARE") + || is_unquoted_kw(next, "NO") + || is_unquoted_kw(next, "KEY"); + !excluded +} + +fn is_non_condition_or(code: &[&TokenWithSpan], idx: usize) -> bool { + if idx == 0 { + return false; + } + let prev = code[idx - 1]; + let Some(next) = code.get(idx + 1) else { + return false; + }; + if is_unquoted_kw(prev, "CREATE") && is_unquoted_kw(next, "REPLACE") { + return true; + } + let is_dml = is_unquoted_kw(prev, "INSERT") || is_unquoted_kw(prev, "UPDATE"); + is_dml && is_conflict_action(next) +} + +fn is_conflict_action(tok: &TokenWithSpan) -> bool { + let Some(word) = unquoted_word(tok) else { + return false; + }; + matches!( + word.to_ascii_uppercase().as_str(), + "REPLACE" | "IGNORE" | "ABORT" | "FAIL" | "ROLLBACK" + ) +} + +fn is_transaction_chain_and(code: &[&TokenWithSpan], idx: usize) -> bool { + if idx == 0 { + return false; + } + let prev = code[idx - 1]; + if !(is_unquoted_kw(prev, "COMMIT") || is_unquoted_kw(prev, "ROLLBACK")) { + return false; + } + let direct_chain = code + .get(idx + 1) + .is_some_and(|t| is_unquoted_kw(t, "CHAIN")); + let no_chain = code.get(idx + 1).is_some_and(|t| is_unquoted_kw(t, "NO")) + && code + .get(idx + 2) + .is_some_and(|t| is_unquoted_kw(t, "CHAIN")); + direct_chain || no_chain +} + +fn is_wildcard_except(code: &[&TokenWithSpan], idx: usize) -> bool { + idx > 0 && code[idx - 1].token == Token::Mul +} + +fn next_code_idx(tokens: &[TokenWithSpan], mut pos: usize) -> Option { + while pos < tokens.len() { + if !matches!(tokens[pos].token, Token::Whitespace(_) | Token::EOF) { + return Some(pos); + } + pos += 1; + } + None +} + +fn unquoted_word(tok: &TokenWithSpan) -> Option<&str> { + match &tok.token { + Token::Word(w) if w.quote_style.is_none() => Some(w.value.as_str()), + _ => None, + } +} + +fn is_unquoted_kw(tok: &TokenWithSpan, expected: &str) -> bool { + unquoted_word(tok).is_some_and(|w| w.eq_ignore_ascii_case(expected)) +} diff --git a/plugins/languages/sql/src/tokenize.rs b/plugins/languages/sql/src/tokenize.rs new file mode 100644 index 00000000..23f10bc6 --- /dev/null +++ b/plugins/languages/sql/src/tokenize.rs @@ -0,0 +1,594 @@ +use std::collections::BTreeSet; + +use codeint_model::{LowerError, Token as ModelToken, TokenKind, token_text_hash}; +use sqlparser::dialect::{ + Dialect, DuckDbDialect, GenericDialect, MySqlDialect, PostgreSqlDialect, SQLiteDialect, +}; +use sqlparser::keywords::Keyword; +use sqlparser::tokenizer::{Token, TokenWithSpan, Tokenizer}; + +use crate::SqlDialect; +use crate::source_set::parse_dollar_tag; + +static GENERIC: GenericDialect = GenericDialect; +static POSTGRESQL: PostgreSqlDialect = PostgreSqlDialect {}; +static MYSQL: MySqlDialect = MySqlDialect {}; +static SQLITE: SQLiteDialect = SQLiteDialect {}; +static DUCKDB: DuckDbDialect = DuckDbDialect; + +pub(crate) fn sqlparser_dialect(dialect: SqlDialect) -> &'static dyn Dialect { + match dialect { + SqlDialect::Generic => &GENERIC, + SqlDialect::Postgresql => &POSTGRESQL, + SqlDialect::Mysql => &MYSQL, + SqlDialect::Sqlite => &SQLITE, + SqlDialect::Duckdb => &DUCKDB, + } +} + +pub(crate) struct TokenChunk { + pub(crate) tokens: Vec, + pub(crate) is_custom_delimited: bool, +} + +pub(crate) struct TokenizedFile { + pub(crate) chunks: Vec, + pub(crate) command_lines: BTreeSet, +} + +pub(crate) fn tokenize_source( + source: &str, + dialect: SqlDialect, +) -> Result { + let normalized = normalize_source(source); + match dialect { + SqlDialect::Mysql => tokenize_mysql(&normalized), + SqlDialect::Duckdb | SqlDialect::Postgresql => { + tokenize_with_cli_commands(&normalized, dialect) + } + SqlDialect::Generic | SqlDialect::Sqlite => tokenize_plain(&normalized, dialect), + } +} + +fn normalize_source(source: &str) -> String { + let stripped = source.strip_prefix('\u{feff}').unwrap_or(source); + if stripped.contains('\r') { + stripped.replace("\r\n", "\n").replace('\r', "\n") + } else { + stripped.to_owned() + } +} + +fn tokenize_plain(source: &str, dialect: SqlDialect) -> Result { + let tokens = run_tokenizer(source, dialect, 1)?; + Ok(TokenizedFile { + chunks: vec![TokenChunk { + tokens, + is_custom_delimited: false, + }], + command_lines: BTreeSet::new(), + }) +} + +fn run_tokenizer( + source: &str, + dialect: SqlDialect, + base_line: u32, +) -> Result, LowerError> { + let mut tokens = Tokenizer::new(sqlparser_dialect(dialect), source) + .tokenize_with_location() + .map_err(|err| LowerError::Unparsable { + message: err.to_string(), + })?; + let line_offset = u64::from(base_line.saturating_sub(1)); + if line_offset > 0 { + shift_token_lines(&mut tokens, line_offset); + } + Ok(tokens) +} + +pub(crate) fn tokenize_pg_routine_body(body: &str, base_line: u32) -> Option> { + let mut tokens = Tokenizer::new(&POSTGRESQL, body) + .tokenize_with_location() + .ok()?; + let line_offset = u64::from(base_line.saturating_sub(1)); + if line_offset > 0 { + shift_token_lines(&mut tokens, line_offset); + } + Some(tokens) +} + +fn shift_token_lines(tokens: &mut [TokenWithSpan], offset: u64) { + for tok in tokens { + if tok.span.start.line > 0 { + tok.span.start.line = tok.span.start.line.saturating_add(offset); + } + if tok.span.end.line > 0 { + tok.span.end.line = tok.span.end.line.saturating_add(offset); + } + } +} + +#[derive(Clone, PartialEq, Eq)] +enum ScanState { + Normal, + SingleQuote, + DoubleQuote, + Backtick, + BlockComment(usize), + DollarQuote(Vec), + CopyPayload, +} + +fn tokenize_with_cli_commands( + source: &str, + dialect: SqlDialect, +) -> Result { + let mut state = ScanState::Normal; + let mut cleaned = String::with_capacity(source.len()); + let mut command_lines = BTreeSet::new(); + + for (idx, line) in source.split('\n').enumerate() { + let line_no = u32::try_from(idx + 1).map_err(|_| LowerError::TooLarge)?; + if idx > 0 { + cleaned.push('\n'); + } + process_cli_line( + line, + line_no, + dialect, + &mut state, + &mut cleaned, + &mut command_lines, + ); + } + + let tokens = run_tokenizer(&cleaned, dialect, 1)?; + Ok(TokenizedFile { + chunks: vec![TokenChunk { + tokens, + is_custom_delimited: false, + }], + command_lines, + }) +} + +fn process_cli_line( + line: &str, + line_no: u32, + dialect: SqlDialect, + state: &mut ScanState, + cleaned: &mut String, + command_lines: &mut BTreeSet, +) { + if *state == ScanState::CopyPayload { + cleaned.push_str(line); + if line == "\\." { + *state = ScanState::Normal; + } + return; + } + if *state == ScanState::Normal && is_cli_command_line(line, dialect) { + command_lines.insert(line_no); + return; + } + cleaned.push_str(line); + advance_scan_state(line, state, true, false); + if dialect == SqlDialect::Postgresql + && *state == ScanState::Normal + && is_pg_copy_from_stdin_line(line) + { + *state = ScanState::CopyPayload; + } +} + +fn is_cli_command_line(line: &str, dialect: SqlDialect) -> bool { + let trimmed = line.trim_start(); + match dialect { + SqlDialect::Duckdb => trimmed + .strip_prefix('.') + .and_then(|rest| rest.chars().next()) + .is_some_and(|ch| ch.is_ascii_alphabetic()), + SqlDialect::Postgresql => trimmed.starts_with('\\'), + _ => false, + } +} + +fn is_pg_copy_from_stdin_line(line: &str) -> bool { + let upper = line.to_ascii_uppercase(); + let trimmed = upper.trim(); + trimmed.starts_with("COPY ") && trimmed.contains("FROM STDIN") && trimmed.ends_with(';') +} + +struct MysqlRawChunk { + text: String, + base_line: u32, + is_custom_delimited: bool, +} + +fn tokenize_mysql(source: &str) -> Result { + let raw_chunks = split_mysql_by_delimiters(source)?; + let mut chunks = Vec::with_capacity(raw_chunks.len()); + for raw in raw_chunks { + if raw.text.trim().is_empty() { + continue; + } + let tokens = run_tokenizer(&raw.text, SqlDialect::Mysql, raw.base_line)?; + chunks.push(TokenChunk { + tokens, + is_custom_delimited: raw.is_custom_delimited, + }); + } + Ok(TokenizedFile { + chunks, + command_lines: BTreeSet::new(), + }) +} + +fn split_mysql_by_delimiters(source: &str) -> Result, LowerError> { + let mut active_delim = ";".to_owned(); + let mut state = ScanState::Normal; + let mut out = Vec::new(); + let mut buf = String::new(); + let mut buf_base_line = 1u32; + + for (idx, line) in source.split('\n').enumerate() { + let line_no = u32::try_from(idx + 1).map_err(|_| LowerError::TooLarge)?; + if state == ScanState::Normal + && let Some(new_delim) = parse_mysql_delimiter_directive(line) + { + flush_mysql_chunk(&mut buf, buf_base_line, active_delim != ";", &mut out); + active_delim = new_delim; + buf_base_line = line_no + 1; + continue; + } + if active_delim == ";" { + append_line_to_buf(&mut buf, &mut buf_base_line, line, line_no); + advance_scan_state(line, &mut state, false, true); + } else { + process_custom_delim_line( + line, + line_no, + &active_delim, + &mut state, + &mut buf, + &mut buf_base_line, + &mut out, + ); + } + } + + flush_mysql_chunk(&mut buf, buf_base_line, active_delim != ";", &mut out); + Ok(out) +} + +fn parse_mysql_delimiter_directive(line: &str) -> Option { + let trimmed = line.trim(); + let rest = trimmed + .get(..9) + .filter(|prefix| prefix.eq_ignore_ascii_case("DELIMITER")) + .and_then(|_| trimmed.get(9..))?; + if !rest.starts_with(char::is_whitespace) { + return None; + } + let delim = rest.split_whitespace().next()?; + (!delim.is_empty()).then(|| delim.to_owned()) +} + +fn append_line_to_buf(buf: &mut String, base_line: &mut u32, line: &str, line_no: u32) { + if buf.is_empty() { + *base_line = line_no; + } else { + buf.push('\n'); + } + buf.push_str(line); +} + +fn flush_mysql_chunk( + buf: &mut String, + base_line: u32, + is_custom_delimited: bool, + out: &mut Vec, +) { + if !buf.trim().is_empty() { + out.push(MysqlRawChunk { + text: std::mem::take(buf), + base_line, + is_custom_delimited, + }); + } else { + buf.clear(); + } +} + +fn process_custom_delim_line( + line: &str, + line_no: u32, + delim: &str, + state: &mut ScanState, + buf: &mut String, + base_line: &mut u32, + out: &mut Vec, +) { + let bytes = line.as_bytes(); + let delim_bytes = delim.as_bytes(); + let mut pos = 0usize; + let mut seg_start = 0usize; + + while pos < bytes.len() { + if *state == ScanState::Normal && bytes[pos..].starts_with(delim_bytes) { + append_segment( + buf, + base_line, + &line[seg_start..pos], + line_no, + seg_start == 0, + ); + flush_mysql_chunk(buf, *base_line, true, out); + pos += delim_bytes.len(); + seg_start = pos; + *base_line = line_no; + continue; + } + pos = step_scan_state(bytes, pos, state, false, true); + } + + if seg_start < line.len() { + append_segment(buf, base_line, &line[seg_start..], line_no, seg_start == 0); + } else if !buf.is_empty() && seg_start == 0 { + buf.push('\n'); + } +} + +fn append_segment( + buf: &mut String, + base_line: &mut u32, + segment: &str, + line_no: u32, + at_line_start: bool, +) { + if buf.is_empty() { + *base_line = line_no; + } else if at_line_start { + buf.push('\n'); + } + buf.push_str(segment); +} + +fn advance_scan_state(line: &str, state: &mut ScanState, nested_comments: bool, mysql_mode: bool) { + let bytes = line.as_bytes(); + let mut pos = 0usize; + while pos < bytes.len() { + pos = step_scan_state(bytes, pos, state, nested_comments, mysql_mode); + } +} + +fn step_scan_state( + bytes: &[u8], + pos: usize, + state: &mut ScanState, + nested_comments: bool, + mysql_mode: bool, +) -> usize { + match state { + ScanState::Normal => step_normal_state(bytes, pos, state, mysql_mode), + ScanState::SingleQuote => step_quote_state(bytes, pos, b'\'', mysql_mode, state), + ScanState::DoubleQuote => step_quote_state(bytes, pos, b'"', mysql_mode, state), + ScanState::Backtick => step_quote_state(bytes, pos, b'`', false, state), + ScanState::BlockComment(depth) => { + step_block_comment_state(bytes, pos, *depth, nested_comments, state) + } + ScanState::DollarQuote(tag) => step_dollar_quote_state(bytes, pos, tag.clone(), state), + ScanState::CopyPayload => bytes.len(), + } +} + +fn step_normal_state(bytes: &[u8], pos: usize, state: &mut ScanState, mysql_mode: bool) -> usize { + if let Some(next) = try_enter_comment(bytes, pos, state, mysql_mode) { + return next; + } + try_enter_quote(bytes, pos, state, mysql_mode).unwrap_or(pos + 1) +} + +fn try_enter_comment( + bytes: &[u8], + pos: usize, + state: &mut ScanState, + mysql_mode: bool, +) -> Option { + let ch = bytes[pos]; + if ch == b'-' && bytes.get(pos + 1) == Some(&b'-') { + return Some(bytes.len()); + } + if mysql_mode && ch == b'#' { + return Some(bytes.len()); + } + if ch == b'/' && bytes.get(pos + 1) == Some(&b'*') { + *state = ScanState::BlockComment(1); + return Some(pos + 2); + } + None +} + +fn try_enter_quote( + bytes: &[u8], + pos: usize, + state: &mut ScanState, + mysql_mode: bool, +) -> Option { + match bytes[pos] { + b'\'' => { + *state = ScanState::SingleQuote; + Some(pos + 1) + } + b'"' => { + *state = ScanState::DoubleQuote; + Some(pos + 1) + } + b'`' => { + *state = ScanState::Backtick; + Some(pos + 1) + } + b'$' if !mysql_mode => { + let tag = parse_dollar_tag(bytes, pos)?; + let len = tag.len(); + *state = ScanState::DollarQuote(tag.to_vec()); + Some(pos + len) + } + _ => None, + } +} + +fn step_quote_state( + bytes: &[u8], + pos: usize, + quote: u8, + backslash_escape: bool, + state: &mut ScanState, +) -> usize { + if backslash_escape && bytes[pos] == b'\\' && pos + 1 < bytes.len() { + return pos + 2; + } + if bytes[pos] == quote { + if bytes.get(pos + 1) == Some("e) { + return pos + 2; + } + *state = ScanState::Normal; + } + pos + 1 +} + +fn step_block_comment_state( + bytes: &[u8], + pos: usize, + depth: usize, + nested: bool, + state: &mut ScanState, +) -> usize { + if nested && bytes[pos] == b'/' && bytes.get(pos + 1) == Some(&b'*') { + *state = ScanState::BlockComment(depth + 1); + return pos + 2; + } + if bytes[pos] == b'*' && bytes.get(pos + 1) == Some(&b'/') { + *state = if depth <= 1 { + ScanState::Normal + } else { + ScanState::BlockComment(depth - 1) + }; + return pos + 2; + } + pos + 1 +} + +fn step_dollar_quote_state(bytes: &[u8], pos: usize, tag: Vec, state: &mut ScanState) -> usize { + if bytes[pos..].starts_with(&tag) { + *state = ScanState::Normal; + return pos + tag.len(); + } + pos + 1 +} + +pub(crate) fn collect_statement_lines_and_tokens( + tokens: &[TokenWithSpan], + routine_bodies: &[Vec], + code_lines: &mut BTreeSet, + out: &mut Vec, +) { + let mut body_iter = routine_bodies.iter(); + for tok in tokens { + if matches!(tok.token, Token::Whitespace(_) | Token::EOF) { + continue; + } + if matches!(tok.token, Token::DollarQuotedString(_)) + && let Some(body_tokens) = body_iter.next() + { + collect_dollar_body(tok, body_tokens, code_lines, out); + continue; + } + insert_span_lines(tok, code_lines); + if let Some(model_tok) = to_model_token(tok) { + out.push(model_tok); + } + } +} + +fn collect_dollar_body( + outer: &TokenWithSpan, + body_tokens: &[TokenWithSpan], + code_lines: &mut BTreeSet, + out: &mut Vec, +) { + if outer.span.start.line > 0 { + code_lines.insert(outer.span.start.line as u32); + } + if outer.span.end.line > 0 { + code_lines.insert(outer.span.end.line as u32); + } + for tok in body_tokens { + if matches!(tok.token, Token::Whitespace(_) | Token::EOF) { + continue; + } + insert_span_lines(tok, code_lines); + if let Some(model_tok) = to_model_token(tok) { + out.push(model_tok); + } + } +} + +fn insert_span_lines(tok: &TokenWithSpan, code_lines: &mut BTreeSet) { + let start = tok.span.start.line as u32; + let end = tok.span.end.line as u32; + if start == 0 { + return; + } + let last = end.max(start); + for line in start..=last { + code_lines.insert(line); + } +} + +fn to_model_token(tok: &TokenWithSpan) -> Option { + if matches!(tok.token, Token::Whitespace(_) | Token::EOF) { + return None; + } + let line = tok.span.start.line as u32; + let (kind, normalized_text) = classify_token(&tok.token); + Some(ModelToken { + kind, + text_hash: token_text_hash(&normalized_text), + line, + }) +} + +fn classify_token(token: &Token) -> (TokenKind, String) { + match token { + Token::Word(word) => { + if word.quote_style.is_none() && word.keyword != Keyword::NoKeyword { + (TokenKind::Other, word.value.to_ascii_uppercase()) + } else { + (TokenKind::Identifier, word.value.clone()) + } + } + Token::Number(_, _) + | Token::SingleQuotedString(_) + | Token::DoubleQuotedString(_) + | Token::TripleSingleQuotedString(_) + | Token::TripleDoubleQuotedString(_) + | Token::DollarQuotedString(_) + | Token::SingleQuotedByteStringLiteral(_) + | Token::DoubleQuotedByteStringLiteral(_) + | Token::TripleSingleQuotedByteStringLiteral(_) + | Token::TripleDoubleQuotedByteStringLiteral(_) + | Token::SingleQuotedRawStringLiteral(_) + | Token::DoubleQuotedRawStringLiteral(_) + | Token::TripleSingleQuotedRawStringLiteral(_) + | Token::TripleDoubleQuotedRawStringLiteral(_) + | Token::NationalStringLiteral(_) + | Token::QuoteDelimitedStringLiteral(_) + | Token::NationalQuoteDelimitedStringLiteral(_) + | Token::EscapedStringLiteral(_) + | Token::UnicodeStringLiteral(_) + | Token::HexStringLiteral(_) => (TokenKind::Literal, token.to_string()), + _ => (TokenKind::Other, token.to_string()), + } +} diff --git a/plugins/languages/sql/tests/conformance.rs b/plugins/languages/sql/tests/conformance.rs new file mode 100644 index 00000000..95863c7e --- /dev/null +++ b/plugins/languages/sql/tests/conformance.rs @@ -0,0 +1,658 @@ +use codeint_lang_sql::{RejectedSqlStatement, Sql, SqlDialect, SqlLowerOutput, flagged_line_rules}; +use codeint_model::{LanguagePlugin, LowerError, RepoPath, SourceSet, TokenKind}; + +fn repo_path(path: &str) -> RepoPath { + RepoPath::new(path).unwrap() +} + +fn lower_generic(path: &str, src: &str) -> SqlLowerOutput { + Sql::new() + .lower_with_details(&repo_path(path), src) + .unwrap_or_else(|err| panic!("expected {path} to lower cleanly: {err}")) +} + +fn lower_dialect(dialect: SqlDialect, path: &str, src: &str) -> SqlLowerOutput { + Sql::with_dialect(dialect) + .lower_with_details(&repo_path(path), src) + .unwrap_or_else(|err| panic!("expected {path} ({dialect}) to lower cleanly: {err}")) +} + +#[test] +fn sql_plugin_shell_dialects_empty_comments_and_unparsable_files() { + let sql = Sql::default(); + assert_eq!(sql.name(), "sql"); + assert_eq!(sql.dialect(), SqlDialect::Generic); + assert_eq!(sql.extensions(), ["sql"]); + assert!(!sql.has_imports()); + assert!(!sql.has_hazard_rules()); + assert!(sql.hazard_rules().is_empty()); + assert!( + sql.reference_ranges() + .unwrap() + .for_metric("erosion") + .is_none() + ); + assert!(sql.manifest_paths(&[repo_path("schema.sql")]).is_empty()); + assert!(sql.workspace_packages(Vec::new()).unwrap().is_empty()); + assert!( + sql.resolve_imports(&[], Vec::new(), Vec::new()) + .unwrap() + .is_empty() + ); + assert!(sql.declared_dependencies(Vec::new()).unwrap().is_empty()); + assert!(sql.entry_points(&[], Vec::new()).unwrap().is_empty()); + + let dialect_labels: Vec<(&str, &str, String)> = [ + SqlDialect::Generic, + SqlDialect::Postgresql, + SqlDialect::Mysql, + SqlDialect::Sqlite, + SqlDialect::Duckdb, + ] + .into_iter() + .map(|d| (d.as_str(), d.display_name(), d.to_string())) + .collect(); + assert_eq!( + dialect_labels, + [ + ("generic", "generic SQL", "generic SQL".to_owned()), + ("postgresql", "postgresql", "postgresql".to_owned()), + ("mysql", "mysql", "mysql".to_owned()), + ("sqlite", "sqlite", "sqlite".to_owned()), + ("duckdb", "duckdb", "duckdb".to_owned()), + ] + ); + + let unsupported = sql.lower(&repo_path("notes.txt"), "SELECT 1;\n"); + assert!(matches!( + unsupported, + Err(LowerError::UnsupportedFile { .. }) + )); + + let empty = lower_generic("empty.sql", ""); + assert_eq!(empty.file_model.source_lines, 0); + assert!(empty.file_model.functions.is_empty()); + assert!(empty.file_model.tokens.is_empty()); + assert_eq!(empty.file_model.source_set, SourceSet::Production); + assert!(!empty.file_model.program_start); + assert!(empty.rejected_statements.is_empty()); + assert!(empty.parsed_statements.is_empty()); + + let comment_only = lower_generic( + "comments.sql", + "-- leading comment\n\n/* multi\n line\n comment */\n", + ); + assert_eq!(comment_only.file_model.source_lines, 0); + assert!(comment_only.file_model.functions.is_empty()); + assert!(comment_only.file_model.tokens.is_empty()); + + let unclosed = sql.lower(&repo_path("broken.sql"), "SELECT 'unclosed string"); + assert!(matches!(unclosed, Err(LowerError::Unparsable { .. }))); + + let lf_src = "-- header\n\nSELECT a,\n b\nFROM items;\n"; + let lf = lower_generic("q.sql", lf_src); + let crlf = lower_generic("q.sql", &lf_src.replace('\n', "\r\n")); + assert_eq!(lf.file_model.source_lines, 3); + assert_eq!(crlf.file_model, lf.file_model); +} + +#[test] +fn sql_statements_as_functions_and_object_naming() { + let src = "\ +CREATE TABLE users ( + id INT PRIMARY KEY, + email TEXT +); + +CREATE TABLE IF NOT EXISTS public.orders ( + id INT PRIMARY KEY +); + +CREATE TEMP TABLE scratch (x INT); +CREATE UNLOGGED TABLE cache (k TEXT); +CREATE OR REPLACE VIEW analytics.monthly_totals AS SELECT 1; +CREATE MATERIALIZED VIEW mv_sales AS SELECT 1; +CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS public.idx_users_email ON users (email); +CREATE INDEX ON users (id); +CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy'); + +BEGIN; +INSERT INTO users VALUES (1, 'a@b.com;still-in-string'); +COMMIT; + +SELECT id FROM users +"; + let out = lower_generic("schema.sql", src); + let names: Vec> = out + .file_model + .functions + .iter() + .map(|f| f.name.as_deref()) + .collect(); + assert_eq!( + names, + [ + Some("users"), + Some("public.orders"), + Some("scratch"), + Some("cache"), + Some("analytics.monthly_totals"), + Some("mv_sales"), + Some("public.idx_users_email"), + None, + Some("mood"), + None, + None, + None, + None, + ] + ); + assert_eq!(out.file_model.functions[0].line, 1); + assert_eq!(out.file_model.functions[0].end_line, 4); + assert_eq!(out.file_model.functions[0].source_lines, 4); + assert_eq!(out.file_model.functions.last().unwrap().line, 22); + assert_eq!(out.file_model.functions.last().unwrap().end_line, 22); + + let quoted = lower_generic("quoted.sql", "CREATE TABLE \"public\".\"Users\" (id INT);"); + assert_eq!( + quoted.file_model.functions[0].name.as_deref(), + Some("public.Users") + ); +} + +#[test] +fn sql_decision_points_cognitive_complexity_and_duplication_tokens() { + let src = "\ +SELECT id, + ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) AS rn, + COUNT(*) AS total +FROM employees +GROUP BY id, dept, salary; + +SELECT CASE + WHEN score >= 90 THEN 'A' + WHEN score >= 80 THEN 'B' + ELSE 'C' + END AS grade +FROM results +WHERE created_at BETWEEN '2026-01-01' AND '2026-12-31' + AND active = true + OR override = true; + +SELECT a.id +FROM a +INNER JOIN b ON a.id = b.a_id +LEFT OUTER JOIN c ON b.id = c.b_id +UNION ALL +SELECT d.id FROM d +INTERSECT +SELECT e.id FROM e +EXCEPT +SELECT f.id FROM f; + +SELECT id FROM a WHERE x IN (SELECT id FROM b) AND y IN (SELECT id FROM c); + +SELECT id FROM a WHERE x IN (SELECT id FROM b WHERE z IN (SELECT id FROM c WHERE k = 1 AND m = 2)); +"; + let out = lower_generic("metrics.sql", src); + let scores: Vec<(u32, u32)> = out + .file_model + .functions + .iter() + .map(|f| (f.decision_points, f.cognitive_complexity)) + .collect(); + assert_eq!(scores, [(0, 0), (4, 4), (5, 5), (3, 3), (3, 6),]); + assert!(scores[4].1 > scores[3].1); + + let create_or_replace = + lower_generic("view.sql", "CREATE OR REPLACE VIEW v AS SELECT 1 FROM t;"); + assert_eq!(create_or_replace.file_model.functions[0].decision_points, 0); + + let upper_q = lower_generic("u.sql", "SELECT col_a FROM tbl_a WHERE col_a = 1;"); + let lower_q = lower_generic("l.sql", "select col_b from tbl_b where col_b = 2;"); + assert_eq!( + upper_q.file_model.tokens.len(), + lower_q.file_model.tokens.len() + ); + for (u, l) in upper_q + .file_model + .tokens + .iter() + .zip(lower_q.file_model.tokens.iter()) + { + assert_eq!(u.kind, l.kind); + if u.kind == TokenKind::Other { + assert_eq!(u.text_hash, l.text_hash); + } + } + assert!( + upper_q + .file_model + .tokens + .iter() + .any(|t| t.kind == TokenKind::Identifier) + ); + assert!( + upper_q + .file_model + .tokens + .iter() + .any(|t| t.kind == TokenKind::Literal) + ); +} + +#[test] +fn sql_rejected_statement_keeps_token_metrics_and_does_not_affect_neighbors() { + let src = "\ +SELECT id +FROM orders +WHERE status = 'a' + OR status = 'b' + OR status = 'c'; + +THIS IS NOT VALID SQL SYNTAX AT ALL WHERE x = 1 AND y = 2; + +SELECT dept +FROM employees +GROUP BY dept +HAVING dept = 'sales'; +"; + let out = lower_generic("mixed.sql", src); + assert_eq!(out.file_model.functions.len(), 3); + assert_eq!(out.file_model.functions[1].line, 7); + assert_eq!(out.file_model.functions[1].decision_points, 1); + assert_eq!(out.file_model.functions[1].cognitive_complexity, 1); + assert_eq!(out.parsed_statements.len(), 2); + assert_eq!( + out.rejected_statements, + [RejectedSqlStatement { + path: repo_path("mixed.sql"), + line: 7, + dialect: SqlDialect::Generic, + }] + ); + let flagged: Vec<(u32, &str)> = out + .file_model + .flagged_lines + .iter() + .map(|f| (f.line, f.rule.as_str())) + .collect(); + assert_eq!( + flagged, + [ + (3, "or-chain-collapses-to-in"), + (12, "having-without-aggregate"), + ] + ); +} + +#[test] +fn sql_flagged_line_rules_hits_and_near_misses() { + let rules: Vec<&str> = flagged_line_rules().collect(); + assert_eq!( + rules, + ["or-chain-collapses-to-in", "having-without-aggregate"] + ); + + let or_hits = [ + ( + "SELECT id\nFROM t\nWHERE status = 'a'\n OR status = 'b'\n OR status = 'c';\n", + 3u32, + ), + ( + "SELECT id\nFROM t\nWHERE 1 = code OR 2 = code OR 3 = code;\n", + 3u32, + ), + ( + "SELECT id\nFROM t\nWHERE t.kind = -1 OR t.kind = 0 OR t.kind = 1;\n", + 3u32, + ), + ( + "UPDATE t\nSET active = false\nWHERE role = 'guest' OR role = 'trial' OR role = 'demo';\n", + 3u32, + ), + ]; + for (src, expected_line) in or_hits { + let out = lower_generic("or_hit.sql", src); + let matches: Vec = out + .file_model + .flagged_lines + .iter() + .filter(|f| f.rule == "or-chain-collapses-to-in") + .map(|f| f.line) + .collect(); + assert_eq!(matches, [expected_line], "expected hit on:\n{src}"); + } + + let or_misses = [ + "SELECT id FROM t WHERE status = 'a' OR status = 'b';", + "SELECT id FROM t WHERE a = 1 OR b = 2 OR c = 3;", + "SELECT id FROM t WHERE a = 1 OR a = 2 OR b = 3;", + "SELECT id FROM t WHERE a = b OR a = c OR a = d;", + "SELECT id FROM t WHERE a = f() OR a = g() OR a = h();", + "SELECT id FROM t WHERE a = $1 OR a = $2 OR a = $3;", + "SELECT id FROM t WHERE a = NULL OR a = NULL OR a = NULL;", + "-- WHERE a = 1 OR a = 2 OR a = 3\nSELECT 'a = 1 OR a = 2 OR a = 3' FROM t;", + ]; + for src in or_misses { + let out = lower_generic("or_miss.sql", src); + assert!( + out.file_model.flagged_lines.is_empty(), + "expected no flagged lines for:\n{src}\ngot: {:?}", + out.file_model.flagged_lines + ); + } + + let having_multiline = "\ +SELECT dept +FROM emp +GROUP BY dept +HAVING + dept = 'sales'; +"; + let having_out = lower_generic("having_hit.sql", having_multiline); + assert_eq!(having_out.file_model.flagged_lines.len(), 1); + assert_eq!(having_out.file_model.flagged_lines[0].line, 4); + assert_eq!( + having_out.file_model.flagged_lines[0].rule, + "having-without-aggregate" + ); + + let having_misses = [ + "SELECT dept FROM emp GROUP BY dept HAVING COUNT(*) > 5;", + "SELECT dept FROM emp GROUP BY dept HAVING SUM(salary) > 100 AND dept = 'eng';", + "SELECT dept FROM emp GROUP BY dept HAVING COALESCE(AVG(salary), 0) > 50;", + "SELECT dept FROM emp GROUP BY dept HAVING ARRAY_AGG(id) IS NOT NULL;", + "SELECT dept FROM emp GROUP BY dept HAVING GROUP_CONCAT(name) LIKE '%a%';", + "SELECT dept FROM emp GROUP BY dept HAVING custom_agg(DISTINCT id) > 1;", + "-- HAVING dept = 'sales'\nSELECT 'HAVING dept = 1' FROM emp;", + ]; + for src in having_misses { + let out = lower_generic("having_miss.sql", src); + assert!( + out.file_model.flagged_lines.is_empty(), + "expected no flagged lines for:\n{src}\ngot: {:?}", + out.file_model.flagged_lines + ); + } +} + +#[test] +fn sql_source_set_classification_and_templated_sql() { + let dump_headers = [ + "-- PostgreSQL database dump\nCREATE TABLE a (id INT);\n", + "-- Dumped by pg_dump version 16.0\nCREATE TABLE a (id INT);\n", + "-- MySQL dump 10.13\nCREATE TABLE a (id INT);\n", + "-- MariaDB database dump\nCREATE TABLE a (id INT);\n", + "-- MariaDB dump 10.19\nCREATE TABLE a (id INT);\n", + ]; + for src in dump_headers { + let out = lower_generic("db/dump.sql", src); + assert_eq!(out.file_model.source_set, SourceSet::Generated); + } + + let late_dump = format!( + "{}-- PostgreSQL database dump\nSELECT 1;\n", + "\n".repeat(25) + ); + assert_eq!( + lower_generic("db/late.sql", &late_dump) + .file_model + .source_set, + SourceSet::Production + ); + + for marker in [ + "CREATE TABLE a (id INT);\n--> statement-breakpoint\nCREATE TABLE b (id INT);\n", + "-- atlas:txmode none\nCREATE TABLE a (id INT);\n", + "-- atlas:nolint DS103\nDROP TABLE a;\n", + ] { + assert_eq!( + lower_generic("migrations/001.sql", marker) + .file_model + .source_set, + SourceSet::Generated + ); + } + + for (path, expected) in [ + ( + "prisma/migrations/20260101_init/migration.sql", + SourceSet::Generated, + ), + ( + "apps/web/prisma/migrations/001/migration.sql", + SourceSet::Generated, + ), + ("drizzle/0000_init.sql", SourceSet::Generated), + ("packages/db/drizzle/0001_add.sql", SourceSet::Generated), + ("migrations/001_init.sql", SourceSet::Production), + ("db/migrations/002_users.sql", SourceSet::Production), + ("test/seed.sql", SourceSet::Test), + ("db/tests/queries.sql", SourceSet::Test), + ("sql/fixtures/users.sql", SourceSet::Test), + ("sql/test.sql", SourceSet::Production), + ] { + let out = lower_generic(path, "SELECT 1;\n"); + assert_eq!(out.file_model.source_set, expected, "path {path}"); + } + + for templated in [ + "SELECT * FROM {{ ref('users') }};", + "{% if target.name == 'prod' %}SELECT 1;{% endif %}", + "SELECT * FROM <%= table_name %>;", + ] { + let err = Sql::new() + .lower(&repo_path("models/m.sql"), templated) + .expect_err("expected templated SQL to be rejected"); + assert!( + matches!(err, LowerError::Unparsable { ref message } if message == "templated SQL"), + "unexpected error for {templated}: {err:?}" + ); + } + + let safe_braces = "\ +-- {{ comment template }} +/* {% block comment %} */ +SELECT '{{ single_quoted }}', + \"{{ double_quoted }}\", + $$ {{ dollar_quoted }} $$ +FROM items; +"; + let safe_out = lower_dialect(SqlDialect::Postgresql, "safe.sql", safe_braces); + assert_eq!(safe_out.file_model.functions.len(), 1); + + let safe_backtick = "SELECT `{{ col }}` FROM items;"; + let mysql_safe = lower_dialect(SqlDialect::Mysql, "safe.sql", safe_backtick); + assert_eq!(mysql_safe.file_model.functions.len(), 1); +} + +fn fn_summary(out: &SqlLowerOutput) -> Vec<(Option<&str>, u32, u32, u32, u32)> { + out.file_model + .functions + .iter() + .map(|f| { + ( + f.name.as_deref(), + f.line, + f.end_line, + f.decision_points, + f.cognitive_complexity, + ) + }) + .collect() +} + +#[test] +fn postgresql_dialect_routines_and_backslash_commands() { + let src = "\ +\\set ON_ERROR_STOP on +\\echo 'deploying function' + +CREATE OR REPLACE FUNCTION public.compute_tier(p_total INT, p_active BOOLEAN) +RETURNS TEXT +LANGUAGE plpgsql +AS $$ +-- comment inside body + +DECLARE + v_i INT := 0; +BEGIN + IF p_active AND p_total > 100 THEN + IF p_total > 500 THEN + RETURN 'platinum'; + END IF; + RETURN 'gold'; + ELSIF p_total > 50 THEN + WHILE v_i < 3 LOOP + v_i := v_i + 1; + END LOOP; + RETURN 'silver'; + END IF; + FOR v_i IN 1..2 LOOP + PERFORM 1; + END LOOP; + RETURN 'bronze'; +EXCEPTION + WHEN division_by_zero THEN + RETURN 'error'; +END; +$$; + +DO $block$ +BEGIN + CREATE TEMP TABLE IF NOT EXISTS scratch_pg (id INT); + PERFORM id FROM users FOR UPDATE; + IF EXISTS (SELECT 1 FROM users) THEN + RAISE NOTICE 'ok'; + END IF; + DROP TABLE IF EXISTS scratch_pg; +END; +$block$; + +SELECT id::int, name FROM users WHERE code ~ '^A' AND active; +"; + let out = lower_dialect(SqlDialect::Postgresql, "pg/routines.sql", src); + assert_eq!( + fn_summary(&out), + [ + (Some("public.compute_tier"), 4, 32, 7, 10), + (None, 34, 43, 2, 3), + (None, 45, 45, 1, 1), + ] + ); + assert_eq!(out.file_model.functions[0].source_lines, 27); + assert_eq!(out.parsed_statements.len(), 2); + assert_eq!( + out.rejected_statements, + [RejectedSqlStatement { + path: repo_path("pg/routines.sql"), + line: 34, + dialect: SqlDialect::Postgresql, + }] + ); + assert_eq!(out.file_model.source_lines, 40); +} + +#[test] +fn mysql_dialect_delimiters_routines_and_syntax() { + let src = "\ +# mysql hash comment +DELIMITER // +CREATE DEFINER = 'admin'@'localhost' PROCEDURE refresh_stats(IN p_limit INT) +BEGIN + DECLARE v_done INT DEFAULT 0; + DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_done = 1; + IF p_limit > 0 THEN + WHILE v_done = 0 DO + INSERT INTO stats SET total = 1; + SET v_done = 1; + END WHILE; + ELSEIF p_limit = 0 THEN + DELETE FROM stats WHERE total = 0; + END IF; +END // +DELIMITER ; + +SELECT `id`, `name` FROM `users` LIMIT 10, 20; +"; + let out = lower_dialect(SqlDialect::Mysql, "mysql/proc.sql", src); + assert_eq!( + fn_summary(&out), + [(Some("refresh_stats"), 3, 15, 4, 5), (None, 18, 18, 0, 0),] + ); + assert_eq!(out.parsed_statements.len(), 1); + assert_eq!( + out.rejected_statements, + [RejectedSqlStatement { + path: repo_path("mysql/proc.sql"), + line: 3, + dialect: SqlDialect::Mysql, + }] + ); +} + +#[test] +fn sqlite_dialect_untyped_tables_and_triggers() { + let src = "\ +CREATE TABLE notes (id, body); + +CREATE TEMP TRIGGER notes_after_insert +AFTER INSERT ON notes +FOR EACH ROW +BEGIN + UPDATE audit + SET label = CASE + WHEN NEW.body GLOB 'err*' THEN 'error' + ELSE 'ok' + END + WHERE note_id = NEW.id; + INSERT OR REPLACE INTO [search_index] VALUES (NEW.id, NEW.body); +END; + +SELECT [id] FROM notes WHERE body GLOB 'a*'; +"; + let out = lower_dialect(SqlDialect::Sqlite, "sqlite/app.sql", src); + assert_eq!( + fn_summary(&out), + [ + (Some("notes"), 1, 1, 0, 0), + (Some("notes_after_insert"), 3, 14, 1, 1), + (None, 16, 16, 0, 0), + ] + ); + assert_eq!(out.parsed_statements.len(), 3); + assert!(out.rejected_statements.is_empty()); +} + +#[test] +fn duckdb_dialect_macros_dot_commands_and_syntax() { + let src = "\ +.mode box +.headers on +.timer on + +CREATE OR REPLACE TEMP MACRO add_one(x) AS x + 1; + +CREATE MACRO analytics.top_sales(min_amt) AS TABLE +SELECT * EXCLUDE (internal_notes), + {'nested': {'k': 1}} AS meta, +FROM sales +WHERE amount > min_amt AND active = true +ORDER BY ALL; + +FROM sales SELECT id, amount; +"; + let out = lower_dialect(SqlDialect::Duckdb, "duck/report.sql", src); + assert_eq!( + fn_summary(&out), + [ + (Some("add_one"), 5, 5, 0, 0), + (Some("analytics.top_sales"), 7, 12, 1, 1), + (None, 14, 14, 0, 0), + ] + ); + assert_eq!(out.parsed_statements.len(), 3); + assert!(out.rejected_statements.is_empty()); + assert_eq!(out.file_model.source_lines, 11); +} From 46294fa35b8249a50aa4e311ecd06585df6e5b13 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Tue, 24 Nov 2026 21:14:34 +0800 Subject: [PATCH 03/12] feat(report): add Hazards, rejected statements, and SQL schemas --- crates/report/HOW-TO.md | 3 +- crates/report/src/diff.rs | 84 ++-- crates/report/src/diff/markdown.rs | 20 +- crates/report/src/hazards_tests.rs | 671 +++++++++++++++++++++++++++ crates/report/src/lib.rs | 367 ++++++++++++--- crates/report/src/markdown.rs | 137 +++++- crates/report/src/measurement.rs | 145 ++++-- crates/report/src/report_schema.rs | 73 ++- crates/report/src/sarif.rs | 100 +++- crates/report/src/sarif/tests.rs | 59 ++- crates/report/src/schema.rs | 42 +- crates/report/src/trend.rs | 8 +- crates/report/src/trend/markdown.rs | 20 +- crates/report/tests/report_schema.rs | 52 ++- schema/codeint-report.schema.json | 155 +++++++ 15 files changed, 1720 insertions(+), 216 deletions(-) create mode 100644 crates/report/src/hazards_tests.rs diff --git a/crates/report/HOW-TO.md b/crates/report/HOW-TO.md index 80fce640..c67c4c31 100644 --- a/crates/report/HOW-TO.md +++ b/crates/report/HOW-TO.md @@ -27,8 +27,9 @@ if !report.over_budget().is_empty() { - Pass one `MeasuredLanguage` per Language plugin that ran on the snapshot. - `Report::summarize` splits the merged `CodeModel` by Source set, computes all Metrics per Source set, evaluates Dependency hygiene per Language plugin when manifests are present, and checks every `Budget`. -- Use `Report::summarize_with_options` and `CommitMeasurement::of_languages_with_options` to pass `DependenciesConfig` (including `dependencies.ignore`), `Boundaries`, external Metric plugins, `OwnershipOptions`, and optional precomputed `orphan_files`, `dependency_hygiene`, and `dependency_hygiene_by_language` (used when `--package` evaluates cross-package reachability and workspace hoisting before filtering). +- Use `Report::summarize_with_options`, `Report::summarize_with_extras`, `CommitMeasurement::of_languages_with_options`, and `CommitMeasurement::of_languages_with_full_options` to pass `DependenciesConfig` (including `dependencies.ignore`), `Boundaries`, external Metric plugins, `OwnershipOptions`, `ReportExtras` (`disabled_hazard_rules`, `rejected_statements`, `sql_schemas`), and optional precomputed `orphan_files`, `dependency_hygiene`, and `dependency_hygiene_by_language` (used when `--package` evaluates cross-package reachability and workspace hoisting before filtering). - When two or more Language plugins measure files, the report adds a `languages` section per plugin and omits Reference ranges on the combined totals. +- Hazards is measured only over languages whose `LanguageFacts::has_hazard_rules` is `true` (on both numerator and denominator) and is omitted when no measured language has Hazard line rules; a Hazards Budget passes when Hazards is absent. - When `MeasuredLanguage::has_imports` is `false`, TOON, JSON, and Markdown reports omit `import_cycles`, `orphan_files`, `boundaries`, and `dependencies` for that language and emit a one-line `import_metrics_note`, and SARIF emits no import Findings for files of that language. - Repository totals and Budgets for `import_cycles`, `orphan_files`, `boundaries`, and `dependencies` (including Workspace package `import_cycles`) count only languages with `has_imports: true` on both sides of each ratio, and stay absent when no measured language has imports. - `render` formats the report as `Toon`, `Json`, `Sarif`, or `Markdown`. diff --git a/crates/report/src/diff.rs b/crates/report/src/diff.rs index eeaf72be..e0eb1b25 100644 --- a/crates/report/src/diff.rs +++ b/crates/report/src/diff.rs @@ -4,8 +4,8 @@ use codeint_config::{ Budgets, FindingsShown, NewFindingsRule, RegressionLimit, RegressionLimits, ReportFormat, }; use codeint_metrics::{ - DEV_IN_PRODUCTION_DEPENDENCIES_METRIC_KEY, UNLISTED_DEPENDENCIES_METRIC_KEY, - UNUSED_DEPENDENCIES_METRIC_KEY, + DEV_IN_PRODUCTION_DEPENDENCIES_METRIC_KEY, HAZARDS_METRIC_KEY, + UNLISTED_DEPENDENCIES_METRIC_KEY, UNUSED_DEPENDENCIES_METRIC_KEY, }; use codeint_model::{Metric, SourceSet}; @@ -20,9 +20,10 @@ use crate::sarif::{ListedDependencies, ListedExternalMetric, ListedFindings, Sar use crate::{ BoundaryFindingRow, BudgetFailure, COGNITIVE_COMPLEXITY_KEY, CloneFamilyFinding, CloneGroupFinding, CognitiveComplexityFinding, Decimal, ErodedFunctionFinding, - ExternalMetricFinding, Findings, FlaggedLineRow, ImportCycleFinding, ImportedDependencyRow, - OrphanFileRow, PerSourceSet, ReportError, TEST_GAP_DIFF_NOTE, UnusedDependencyRow, - clustered_clone_group_ids, dependency_over_budget, unlisted_clone_family_group_ids, + ExternalMetricFinding, Findings, FlaggedLineRow, HazardLineRow, ImportCycleFinding, + ImportedDependencyRow, OrphanFileRow, PerSourceSet, ReportError, TEST_GAP_DIFF_NOTE, + UnusedDependencyRow, clustered_clone_group_ids, dependency_over_budget, + unlisted_clone_family_group_ids, }; mod markdown; @@ -113,6 +114,8 @@ struct SourceSetChanges { boundaries: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] orphan_files: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + hazards: Option>, #[serde(default, flatten)] external_metrics: BTreeMap, } @@ -319,6 +322,10 @@ impl DiffReport { .as_ref() .map_or(&[], |orphans| orphans.new.listed.as_slice()), test_gap: &[], + hazards: changes + .hazards + .as_ref() + .map_or(&[], |hazards| hazards.new.listed.as_slice()), external_metrics: changes .external_metrics .iter() @@ -567,6 +574,12 @@ fn over_budget(source_sets: &SourceSetChangesSections, budgets: &Budgets) -> Vec .iter() .map(move |orphans| (source_set, "orphan_files", orphans.head_ratio.0)), ) + .chain( + changes + .hazards + .iter() + .map(move |hazards| (source_set, HAZARDS_METRIC_KEY, hazards.head_ratio.0)), + ) .chain( changes.external_metrics.iter().map(move |(key, metric)| { (source_set, key.as_str(), metric.changes.head_ratio.0) @@ -611,6 +624,9 @@ impl SourceSetChanges { if let Some(orphan_files) = &self.orphan_files { found.extend(orphan_files.regressions(source_set, "orphan_files", limits)); } + if let Some(hazards) = &self.hazards { + found.extend(hazards.regressions(source_set, HAZARDS_METRIC_KEY, limits)); + } for (key, external) in &self.external_metrics { found.extend(external.changes.regressions(source_set, key, limits)); } @@ -834,7 +850,7 @@ impl std::fmt::Display for Regression { } } -const NUMERATOR_KEYS: [(&str, &str); 10] = [ +const NUMERATOR_KEYS: [(&str, &str); 11] = [ ("erosion", "eroded_function_mass"), ("cognitive_complexity", "complex_cognitive_complexity"), ("duplication", "clone_lines"), @@ -842,6 +858,7 @@ const NUMERATOR_KEYS: [(&str, &str); 10] = [ ("import_cycles", "modules_in_import_cycles"), ("boundaries", "boundary_findings"), ("orphan_files", "orphan_files"), + ("hazards", "hazard_lines"), ("unused_dependencies", "unused"), ("unlisted_dependencies", "unlisted"), ("dev_in_production_dependencies", "dev_in_production"), @@ -916,33 +933,10 @@ fn source_set_changes( }, ); } - let import_cycles = match (base.import_cycles, head.import_cycles) { - (None, None) => None, - (base_cycles, head_cycles) => Some(classify( - base_cycles.unwrap_or_default(), - head_cycles.unwrap_or_default(), - shown, - ownership, - )), - }; - let boundaries = match (base.boundaries, head.boundaries) { - (None, None) => None, - (base_boundaries, head_boundaries) => Some(classify( - base_boundaries.unwrap_or_default(), - head_boundaries.unwrap_or_default(), - shown, - ownership, - )), - }; - let orphan_files = match (base.orphan_files, head.orphan_files) { - (None, None) => None, - (base_orphans, head_orphans) => Some(classify( - base_orphans.unwrap_or_default(), - head_orphans.unwrap_or_default(), - shown, - ownership, - )), - }; + let import_cycles = classify_optional(base.import_cycles, head.import_cycles, shown, ownership); + let boundaries = classify_optional(base.boundaries, head.boundaries, shown, ownership); + let orphan_files = classify_optional(base.orphan_files, head.orphan_files, shown, ownership); + let hazards = classify_optional(base.hazards, head.hazards, shown, ownership); let duplication_groups = classify(base.duplication, head.duplication, shown, ownership); let base_families = ownership.apply(base.clone_families); let head_families = ownership.apply(head.clone_families); @@ -982,10 +976,28 @@ fn source_set_changes( import_cycles, boundaries, orphan_files, + hazards, external_metrics, } } +fn classify_optional( + base: Option>, + head: Option>, + shown: FindingsShown, + ownership: OwnershipOptions<'_>, +) -> Option> { + match (base, head) { + (None, None) => None, + (base_metric, head_metric) => Some(classify( + base_metric.unwrap_or_default(), + head_metric.unwrap_or_default(), + shown, + ownership, + )), + } +} + impl Identified for ErodedFunctionFinding { fn id(&self) -> &str { &self.id @@ -1051,3 +1063,9 @@ impl Identified for OrphanFileRow { &self.id } } + +impl Identified for HazardLineRow { + fn id(&self) -> &str { + &self.id + } +} diff --git a/crates/report/src/diff/markdown.rs b/crates/report/src/diff/markdown.rs index 65b208f8..41669d27 100644 --- a/crates/report/src/diff/markdown.rs +++ b/crates/report/src/diff/markdown.rs @@ -5,12 +5,12 @@ use crate::Findings; use crate::markdown::{ BOUNDARY_FINDING_COLUMNS, CLONE_FAMILY, CLONE_GROUP, COMPLEX_FUNCTION, COMPLEX_FUNCTION_COLUMNS, ERODED_FUNCTION, ERODED_FUNCTION_COLUMNS, EXTERNAL_FINDING_COLUMNS, - FINDING, FLAGGED_LINE, FLAGGED_LINE_COLUMNS, IMPORT_CYCLE, IMPORTED_DEPENDENCY_COLUMNS, Noun, - ORPHAN_FILE, ORPHAN_FILE_COLUMNS, UNUSED_DEPENDENCY_COLUMNS, boundary_finding_row, - clone_family_item, clone_group_item, code, complex_function_row, eroded_function_row, - external_finding_row, findings_table, flagged_line_row, import_cycle_item, - imported_dependency_row, list, orphan_file_row, prose, push_findings, sentence_item, table, - unused_dependency_row, + FINDING, FLAGGED_LINE, FLAGGED_LINE_COLUMNS, HAZARD_LINE, HAZARD_LINE_COLUMNS, IMPORT_CYCLE, + IMPORTED_DEPENDENCY_COLUMNS, Noun, ORPHAN_FILE, ORPHAN_FILE_COLUMNS, UNUSED_DEPENDENCY_COLUMNS, + boundary_finding_row, clone_family_item, clone_group_item, code, complex_function_row, + eroded_function_row, external_finding_row, findings_table, flagged_line_row, hazard_line_row, + import_cycle_item, imported_dependency_row, list, orphan_file_row, prose, push_findings, + sentence_item, table, unused_dependency_row, }; const TITLE: &str = "# codeint diff"; @@ -106,6 +106,9 @@ fn metric_rows(source_set: &str, changes: &SourceSetChanges) -> Vec> if let Some(orphan_files) = &changes.orphan_files { rows.push(metric_row(source_set, "Orphan files", orphan_files)); } + if let Some(hazards) = &changes.hazards { + rows.push(metric_row(source_set, "Hazards", hazards)); + } for external in changes.external_metrics.values() { rows.push(metric_row(source_set, &external.name, &external.changes)); } @@ -197,6 +200,11 @@ fn findings_blocks(changes: &SourceSetChanges) -> Vec { |listed| findings_table(&ORPHAN_FILE_COLUMNS, listed, orphan_file_row), ); } + if let Some(hazards) = &changes.hazards { + push_changes(&mut blocks, "Hazards", hazards, &HAZARD_LINE, |listed| { + findings_table(&HAZARD_LINE_COLUMNS, listed, hazard_line_row) + }); + } for external in changes.external_metrics.values() { push_changes( &mut blocks, diff --git a/crates/report/src/hazards_tests.rs b/crates/report/src/hazards_tests.rs new file mode 100644 index 00000000..cd048e27 --- /dev/null +++ b/crates/report/src/hazards_tests.rs @@ -0,0 +1,671 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use codeint_config::{ + Budgets, CalendarDay, CliSchema, Codeowners, DependenciesConfig, DuplicationConfig, + FindingsShown, OwnerFilter, RegressionLimits, ReportFormat, ReportRenderFormat, SchemaFormat, + TrendFormat, +}; +use codeint_model::{ + CodeModel, FileModel, HazardLine, LanguageFacts, ReferenceRanges, RepoPath, SkippedFile, + SourceFile, SourceSet, Token, TokenKind, Workspace, token_text_hash, +}; +use serde_json::Value; + +use crate::{ + BaseCommit, CommitMeasurement, CommitMeasurementOptions, DiffReport, Head, LanguageSchema, + MeasuredLanguage, OwnershipOptions, RejectedStatementEntry, Report, ReportExtras, + ReportOptions, SavedReport, SchemaReport, SqlSchemaSummary, TrendPoint, TrendReport, +}; + +fn sql_file( + path: &str, + source_set: SourceSet, + source_lines: u32, + hazards: &[(u32, &str)], + tokens: Vec, +) -> SourceFile { + SourceFile { + path: RepoPath::new(path).expect("valid path"), + model: FileModel { + source_set, + source_lines, + functions: Vec::new(), + tokens, + flagged_lines: Vec::new(), + hazard_lines: hazards + .iter() + .map(|&(line, rule)| HazardLine { + line, + rule: rule.to_owned(), + }) + .collect(), + runtime_imports: Vec::new(), + program_start: false, + }, + } +} + +fn plain_file(path: &str, source_set: SourceSet, source_lines: u32) -> SourceFile { + sql_file(path, source_set, source_lines, &[], Vec::new()) +} + +fn sql_model(files: Vec, workspace: Workspace) -> CodeModel { + CodeModel { + workspace, + files, + languages: vec![LanguageFacts { + language: "sql".to_owned(), + has_coverage: false, + has_hazard_rules: true, + has_imports: false, + }], + ..CodeModel::default() + } +} + +fn rust_model(files: Vec, workspace: Workspace) -> CodeModel { + CodeModel { + workspace, + files, + languages: vec![LanguageFacts { + language: "rust".to_owned(), + has_coverage: false, + has_hazard_rules: false, + has_imports: true, + }], + ..CodeModel::default() + } +} + +fn measured_sql(model: CodeModel) -> MeasuredLanguage { + MeasuredLanguage { + plugin: "sql".to_owned(), + model, + reference_ranges: ReferenceRanges::default(), + has_imports: false, + } +} + +fn measured_rust(model: CodeModel) -> MeasuredLanguage { + MeasuredLanguage { + plugin: "rust".to_owned(), + model, + reference_ranges: ReferenceRanges::default(), + has_imports: true, + } +} + +fn default_report_options<'a>( + budgets: &'a Budgets, + dependencies: &'a DependenciesConfig, +) -> ReportOptions<'a> { + ReportOptions { + findings: FindingsShown::default(), + budgets, + metric_plugins: &[], + boundaries: None, + dependencies, + dependency_hygiene: None, + dependency_hygiene_by_language: None, + duplication: DuplicationConfig::default(), + orphan_files: None, + orphan_files_by_language: None, + ownership: OwnershipOptions::default(), + coverage_reports_named: false, + unmatched_coverage_paths: &[], + } +} + +fn config_from_json(json_text: &str) -> codeint_config::Configuration { + use std::sync::atomic::{AtomicU64, Ordering}; + + static COUNTER: AtomicU64 = AtomicU64::new(0); + let unique = COUNTER.fetch_add(1, Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!( + "codeint-report-hazards-test-{}-{unique}", + std::process::id() + )); + std::fs::create_dir_all(&dir).expect("create temp dir"); + std::fs::write(dir.join("codeint.json"), json_text).expect("write config"); + let loaded = codeint_config::read_configuration(&dir); + let _ = std::fs::remove_dir_all(&dir); + loaded.expect("load config") +} + +fn find_entry<'a>(array: &'a Value, key: &str, expected: &str) -> &'a Value { + array + .as_array() + .expect("array") + .iter() + .find(|entry| entry[key] == expected) + .expect("matching entry") +} + +fn parse_json(text: &str) -> Value { + serde_json::from_str(text).expect("valid JSON") +} + +fn array_len(value: &Value) -> usize { + value.as_array().expect("JSON array").len() +} + +fn assert_hazards_summary(section: &Value, hazard_lines: u64, source_lines: u64, ratio: f64) { + assert_eq!(section["hazard_lines"], hazard_lines); + assert_eq!(section["source_lines"], source_lines); + assert_eq!(section["ratio"], ratio); +} + +fn budgets_from_json(json_text: &str) -> Budgets { + config_from_json(json_text).budgets +} + +fn limits_from_json(json_text: &str) -> RegressionLimits { + config_from_json(json_text).regression_limits +} + +#[test] +fn non_hazard_languages_omit_hazards_and_pass_hazards_budget() { + let budgets = budgets_from_json(r#"{ "budgets": { "production": { "hazards": 0.0 } } }"#); + let model = rust_model( + vec![plain_file("src/lib.rs", SourceSet::Production, 50)], + Workspace::default(), + ); + let empty_sql = sql_model(Vec::new(), Workspace::default()); + let report = Report::summarize( + vec![measured_rust(model), measured_sql(empty_sql)], + Vec::new(), + FindingsShown::default(), + &budgets, + ); + + assert!(report.over_budget().is_empty()); + let json: Value = + serde_json::from_str(&report.render(ReportFormat::Json).expect("json")).expect("parse"); + assert!( + json["source_sets"]["production"].get("hazards").is_none(), + "non-hazard repo must omit hazards even when sql plugin has zero files" + ); + let markdown = report.render(ReportFormat::Markdown).expect("markdown"); + assert!(!markdown.contains("Hazards")); + let sarif: Value = + serde_json::from_str(&report.render(ReportFormat::Sarif).expect("sarif")).expect("sarif"); + assert!( + sarif["runs"][0]["results"] + .as_array() + .expect("results") + .is_empty() + ); +} + +#[test] +fn multi_language_hazards_denominator_excludes_languages_without_hazard_rules() { + let workspace = Workspace::new([ + RepoPath::new("packages/api").expect("api"), + RepoPath::new("packages/web").expect("web"), + ]); + let rust = rust_model( + vec![ + plain_file("packages/api/src/lib.rs", SourceSet::Production, 100), + plain_file("packages/api/tests/it.rs", SourceSet::Test, 50), + plain_file("packages/web/src/app.rs", SourceSet::Production, 80), + ], + workspace.clone(), + ); + let sql = sql_model( + vec![ + sql_file( + "packages/api/db/query.sql", + SourceSet::Production, + 10, + &[(2, "select-star"), (2, "order-by-random"), (5, "drop")], + Vec::new(), + ), + sql_file( + "packages/api/db/dump.sql", + SourceSet::Generated, + 4, + &[(1, "truncate")], + Vec::new(), + ), + ], + workspace, + ); + let report = Report::summarize( + vec![measured_rust(rust), measured_sql(sql)], + Vec::new(), + FindingsShown::default(), + &Budgets::default(), + ); + + let json = parse_json(&report.render(ReportFormat::Json).expect("json")); + let prod_hazards = &json["source_sets"]["production"]["hazards"]; + assert_hazards_summary(prod_hazards, 2, 10, 0.2); + assert_eq!( + array_len(&prod_hazards["findings"]), + 3, + "same line with two rules counts as one hazard line and two findings" + ); + assert!( + json["source_sets"]["test"].get("hazards").is_none(), + "test source set has only rust files so hazards must be absent" + ); + assert_hazards_summary(&json["source_sets"]["generated"]["hazards"], 1, 4, 0.25); + + assert!( + json["languages"]["rust"]["source_sets"]["production"] + .get("hazards") + .is_none() + ); + assert_eq!( + json["languages"]["sql"]["source_sets"]["production"]["hazards"]["ratio"], + 0.2 + ); + + let packages = &json["source_sets"]["production"]["packages"]; + let api_pkg = find_entry(packages, "path", "packages/api"); + assert_eq!(api_pkg["hazards"]["hazard_lines"], 2); + assert_eq!(api_pkg["hazards"]["source_lines"], 10); + assert_eq!(api_pkg["hazards"]["ratio"], 0.2); + let web_pkg = find_entry(packages, "path", "packages/web"); + assert!(web_pkg.get("hazards").is_none()); + + let markdown = report.render(ReportFormat::Markdown).expect("markdown"); + assert!( + markdown.contains("| Production | Hazards | 0.2 | 2 of 10 Hazard lines | not applicable |") + ); + assert!(markdown.contains("### Hazards")); + assert!(markdown.contains("| Path | Line | Rule |")); + assert!(markdown.contains("| `packages/api/db/query.sql` | 2 | select-star |")); + assert!(markdown.contains("| `packages/web` |")); + assert!(markdown.contains("| not measured |")); +} + +#[test] +fn disabled_hazard_rules_and_budgets_equal_and_over() { + let model = sql_model( + vec![sql_file( + "db/queries.sql", + SourceSet::Production, + 10, + &[(2, "select-star"), (6, "delete-without-filter")], + Vec::new(), + )], + Workspace::default(), + ); + let dependencies = DependenciesConfig::default(); + + let equal_budget = budgets_from_json(r#"{ "budgets": { "production": { "hazards": 0.2 } } }"#); + let equal_report = Report::summarize_with_extras( + vec![measured_sql(model.clone())], + Vec::new(), + default_report_options(&equal_budget, &dependencies), + ReportExtras::default(), + ) + .expect("equal budget report"); + assert!(equal_report.over_budget().is_empty()); + + let tighter_budget = + budgets_from_json(r#"{ "budgets": { "production": { "hazards": 0.1 } } }"#); + let over_report = Report::summarize_with_extras( + vec![measured_sql(model.clone())], + Vec::new(), + default_report_options(&tighter_budget, &dependencies), + ReportExtras::default(), + ) + .expect("over budget report"); + assert_eq!(over_report.over_budget().len(), 1); + assert!( + over_report.over_budget()[0] + .to_string() + .contains("production hazards ratio 0.2 is over its Budget 0.1") + ); + + let disabled = BTreeSet::from(["select-star".to_owned()]); + let disabled_report = Report::summarize_with_extras( + vec![measured_sql(model)], + Vec::new(), + default_report_options(&tighter_budget, &dependencies), + ReportExtras::default().with_disabled_hazard_rules(disabled), + ) + .expect("disabled rule report"); + assert!(disabled_report.over_budget().is_empty()); + let json: Value = + serde_json::from_str(&disabled_report.render(ReportFormat::Json).expect("json")) + .expect("parse"); + assert_eq!(json["source_sets"]["production"]["hazards"]["ratio"], 0.1); + assert_eq!( + json["source_sets"]["production"]["hazards"]["findings"] + .as_array() + .map(Vec::len), + Some(1) + ); +} + +#[test] +fn rejected_statements_sql_schemas_templated_skipped_and_zero_secret_leakage() { + let secret = "SUPER_SECRET_PASSWORD_987654"; + let mut model = sql_model( + vec![sql_file( + "db/auth.sql", + SourceSet::Production, + 5, + &[(3, "plain-text-secret")], + vec![Token { + kind: TokenKind::Literal, + text_hash: token_text_hash(secret), + line: 3, + }], + )], + Workspace::default(), + ); + model.skipped.push(SkippedFile { + path: RepoPath::new("db/template.sql").expect("path"), + reason: "templated SQL".to_owned(), + }); + let budgets = Budgets::default(); + let dependencies = DependenciesConfig::default(); + let codeowners = Codeowners::parse("db/* @data-team\n"); + let owner_filter = OwnerFilter::new("@data-team").expect("owner filter"); + let mut options = default_report_options(&budgets, &dependencies); + options.ownership = OwnershipOptions { + codeowners: Some(&codeowners), + owner_filter: Some(&owner_filter), + }; + let extras = ReportExtras::default() + .with_rejected_statements(vec![RejectedStatementEntry { + path: "db/broken.sql".to_owned(), + line: 14, + dialect: "postgresql".to_owned(), + }]) + .with_sql_schemas(vec![ + SqlSchemaSummary { + package: None, + dialect: "postgresql".to_owned(), + tables: 4, + }, + SqlSchemaSummary { + package: Some("packages/billing".to_owned()), + dialect: "generic".to_owned(), + tables: 2, + }, + ]); + + let report = + Report::summarize_with_extras(vec![measured_sql(model)], Vec::new(), options, extras) + .expect("summarize"); + + let json_text = report.render(ReportFormat::Json).expect("json"); + let toon_text = report.render(ReportFormat::Toon).expect("toon"); + let md_text = report.render(ReportFormat::Markdown).expect("markdown"); + let sarif_text = report.render(ReportFormat::Sarif).expect("sarif"); + + for (label, output) in [ + ("json", &json_text), + ("toon", &toon_text), + ("markdown", &md_text), + ("sarif", &sarif_text), + ] { + assert!(!output.contains(secret), "{label} leaked secret text"); + } + + let json: Value = serde_json::from_str(&json_text).expect("parse json"); + assert_eq!(json["rejected_statements"][0]["path"], "db/broken.sql"); + assert_eq!(json["rejected_statements"][0]["line"], 14); + assert_eq!(json["rejected_statements"][0]["dialect"], "postgresql"); + assert!(json["sql_schemas"][0].get("package").is_none()); + assert_eq!(json["sql_schemas"][0]["dialect"], "postgresql"); + assert_eq!(json["sql_schemas"][0]["tables"], 4); + assert_eq!(json["sql_schemas"][1]["package"], "packages/billing"); + assert_eq!(json["skipped"][0]["reason"], "templated SQL"); + + let finding = &json["source_sets"]["production"]["hazards"]["findings"][0]; + let finding_keys: BTreeSet<&str> = finding + .as_object() + .expect("finding object") + .keys() + .map(String::as_str) + .collect(); + assert_eq!( + finding_keys, + BTreeSet::from(["id", "path", "line", "rule", "owners"]) + ); + + assert!(md_text.contains("| Path | Line | Rule | Owners |")); + assert!(md_text.contains("| `db/auth.sql` | 3 | plain-text-secret | `@data-team` |")); + assert!(md_text.contains("## Rejected statements")); + assert!(md_text.contains("- `db/broken.sql:14`: dialect `postgresql`")); + assert!(md_text.contains("## SQL schemas")); + assert!(md_text.contains("| root | `postgresql` | 4 |")); + assert!(md_text.contains("| `packages/billing` | `generic` | 2 |")); + assert!(md_text.contains("- `db/template.sql`: templated SQL")); + + let saved = SavedReport::from_json(&json_text).expect("saved report round trip"); + assert_eq!( + saved.render(ReportRenderFormat::Markdown).expect("md"), + md_text + ); + assert_eq!( + saved.render(ReportRenderFormat::Sarif).expect("sarif"), + sarif_text + ); +} + +#[test] +fn diff_and_trend_measure_hazards_only_on_hazard_languages_with_limits_budgets_and_sarif() { + let rust = rust_model( + vec![plain_file("src/main.rs", SourceSet::Production, 100)], + Workspace::default(), + ); + let base_sql = sql_model( + vec![sql_file( + "db/q.sql", + SourceSet::Production, + 10, + &[(2, "select-star")], + vec![Token { + kind: TokenKind::Other, + text_hash: token_text_hash("select"), + line: 2, + }], + )], + Workspace::default(), + ); + let head_sql = sql_model( + vec![sql_file( + "db/q.sql", + SourceSet::Production, + 10, + &[(2, "select-star"), (5, "delete-without-filter")], + vec![ + Token { + kind: TokenKind::Other, + text_hash: token_text_hash("select"), + line: 2, + }, + Token { + kind: TokenKind::Other, + text_hash: token_text_hash("delete"), + line: 5, + }, + ], + )], + Workspace::default(), + ); + let dependencies = DependenciesConfig::default(); + let empty_disabled = BTreeSet::new(); + let measure = |models: Vec, disabled: &BTreeSet| { + CommitMeasurement::of_languages_with_full_options( + models, + CommitMeasurementOptions { + metric_plugins: &[], + boundaries: None, + dependencies: &dependencies, + duplication: DuplicationConfig::default(), + orphan_files: None, + dependency_hygiene: None, + disabled_hazard_rules: disabled, + }, + ) + .expect("commit measurement") + }; + + let base_m = measure(vec![rust.clone(), base_sql], &empty_disabled); + let head_m = measure(vec![rust.clone(), head_sql.clone()], &empty_disabled); + let budgets = budgets_from_json(r#"{ "budgets": { "production": { "hazards": 0.15 } } }"#); + let limits = limits_from_json( + r#"{ "regression_limits": { "hazards": { "ratio_rise": 0.05, "new_findings": "any_new_finding" } } }"#, + ); + + let diff = DiffReport::compare( + BaseCommit { + git_ref: "main".to_owned(), + merge_base: "abc1234".to_owned(), + }, + Head::WorkingTree, + base_m, + head_m, + FindingsShown::default(), + &budgets, + &limits, + ); + + let diff_json_text = diff.render(ReportFormat::Json).expect("diff json"); + let diff_json = parse_json(&diff_json_text); + let hazards = &diff_json["source_sets"]["production"]["hazards"]; + assert_eq!( + ( + hazards["base_ratio"].as_f64(), + hazards["head_ratio"].as_f64(), + hazards["unchanged"].as_u64(), + array_len(&hazards["new"]), + array_len(&hazards["resolved"]), + ), + (Some(0.1), Some(0.2), Some(1), 1, 0) + ); + assert_eq!(hazards["new"][0]["rule"], "delete-without-filter"); + + let failures = diff.failure_messages(); + assert!( + failures + .iter() + .any(|msg| msg.contains("production hazards ratio 0.2 is over its Budget 0.15")) + ); + assert!( + failures + .iter() + .any(|msg| msg.contains("production hazards ratio rose from 0.1 to 0.2")) + ); + assert!( + failures + .iter() + .any(|msg| msg.contains("production hazards Metric has 1 new Finding")) + ); + + let diff_md = diff.render(ReportFormat::Markdown).expect("diff md"); + assert!(diff_md.contains("| Production | Hazards | 0.1 | 0.2 | 1 | 0 | 1 |")); + assert!(diff_md.contains("### New Hazards Findings")); + assert!(diff_md.contains("| `db/q.sql` | 5 | delete-without-filter |")); + + let diff_sarif: Value = + serde_json::from_str(&diff.render(ReportFormat::Sarif).expect("diff sarif")) + .expect("parse sarif"); + let sarif_results = diff_sarif["runs"][0]["results"] + .as_array() + .expect("sarif results"); + assert_eq!(sarif_results.len(), 1); + assert_eq!(sarif_results[0]["ruleId"], "delete-without-filter"); + assert_eq!( + sarif_results[0]["locations"][0]["physicalLocation"]["region"]["startLine"], + 5 + ); + let rule_index = sarif_results[0]["ruleIndex"].as_u64().expect("ruleIndex") as usize; + assert_eq!( + diff_sarif["runs"][0]["tool"]["driver"]["rules"][rule_index]["id"], + "delete-without-filter" + ); + + let saved_diff = SavedReport::from_json(&diff_json_text).expect("saved diff"); + assert_eq!( + saved_diff.render(ReportRenderFormat::Sarif).expect("sarif"), + diff.render(ReportFormat::Sarif).expect("sarif") + ); + + let disabled = BTreeSet::from(["delete-without-filter".to_owned()]); + let disabled_head = measure(vec![rust.clone(), head_sql.clone()], &disabled); + let disabled_trend = TrendReport::of(vec![ + TrendPoint { + commit: "1111111".to_owned(), + committed_on: CalendarDay::containing(1_700_000_000), + measurement: measure(vec![rust], &empty_disabled), + }, + TrendPoint { + commit: "2222222".to_owned(), + committed_on: CalendarDay::containing(1_700_086_400), + measurement: disabled_head, + }, + ]); + let trend_json: Value = serde_json::from_str( + &disabled_trend + .render(TrendFormat::Json) + .expect("trend json"), + ) + .expect("parse trend json"); + assert!( + trend_json["source_sets"]["production"][0] + .get("hazards") + .is_none() + ); + assert_eq!(trend_json["source_sets"]["production"][1]["hazards"], 0.1); + let trend_md = disabled_trend + .render(TrendFormat::Markdown) + .expect("trend md"); + assert!(trend_md.contains("| Hazards |")); + assert!(trend_md.contains("| `1111111` |")); + assert!(trend_md.contains("| - |")); + assert!(trend_md.contains("| 0.1 |")); +} + +#[test] +fn schema_report_lists_hazards_metric_and_language_hazard_rules() { + let schema = SchemaReport::build( + CliSchema { + name: "codeint".to_owned(), + version: "0.6.0".to_owned(), + description: "Measure entropy and hazards".to_owned(), + commands: Vec::new(), + output_formats: Vec::new(), + }, + vec![ + LanguageSchema { + name: "rust".to_owned(), + extensions: vec!["rs".to_owned()], + }, + LanguageSchema { + name: "sql".to_owned(), + extensions: vec!["sql".to_owned()], + }, + ], + Vec::new(), + Vec::new(), + ) + .with_language_hazard_rules(BTreeMap::from([( + "sql".to_owned(), + vec!["select-star".to_owned(), "drop".to_owned()], + )])); + + let json: Value = + serde_json::from_str(&schema.render(SchemaFormat::Json).expect("schema json")) + .expect("parse schema"); + let hazards_metric = find_entry(&json["metrics"], "key", "hazards"); + assert_eq!(hazards_metric["name"], "Hazards"); + assert!(hazards_metric["default_ratio_rise_limit"].is_number()); + assert!(hazards_metric["default_new_findings_rule"].is_string()); + + let rust = find_entry(&json["languages"], "name", "rust"); + assert!(rust.get("hazard_rules").is_none()); + let sql = find_entry(&json["languages"], "name", "sql"); + assert_eq!( + sql["hazard_rules"], + serde_json::json!(["select-star", "drop"]) + ); +} diff --git a/crates/report/src/lib.rs b/crates/report/src/lib.rs index f273222d..ab973c19 100644 --- a/crates/report/src/lib.rs +++ b/crates/report/src/lib.rs @@ -1,6 +1,6 @@ #![forbid(unsafe_code)] -use std::collections::{BTreeMap, HashSet}; +use std::collections::{BTreeMap, BTreeSet, HashSet}; use codeint_config::{ AgentFormat, Boundaries as BoundariesConfig, BoundaryDirective, BoundaryRuleDecision, Budgets, @@ -11,9 +11,10 @@ use codeint_metrics::{ Boundaries, BoundaryEdgeCheck, BoundaryFinding, BoundaryPolicy, CloneFamily, CloneGroup, CognitiveComplexity, ComplexFunction, DEV_IN_PRODUCTION_DEPENDENCIES_METRIC_KEY, DependencyHygiene, Duplication, ErodedFunction, Erosion, FlaggedLineFinding, Fragment, - ImportCycle, ImportCycles, MinimumCloneTokens, MinimumDistinctTokens, NearCloneConfig, - OrphanFileFinding, OrphanFiles, TEST_GAP_METRIC_KEY, TestGap, TestGapFinding, - UNLISTED_DEPENDENCIES_METRIC_KEY, UNUSED_DEPENDENCIES_METRIC_KEY, UnresolvedImport, Verbosity, + HAZARDS_METRIC_KEY, HazardLineFinding, Hazards, ImportCycle, ImportCycles, MinimumCloneTokens, + MinimumDistinctTokens, NearCloneConfig, OrphanFileFinding, OrphanFiles, TEST_GAP_METRIC_KEY, + TestGap, TestGapFinding, UNLISTED_DEPENDENCIES_METRIC_KEY, UNUSED_DEPENDENCIES_METRIC_KEY, + UnresolvedImport, Verbosity, }; use codeint_model::{ CodeModel, ExternalFinding, Metric, MetricPlugin, MetricPluginError, Package, ReferenceRange, @@ -30,6 +31,8 @@ mod dependencies; mod diff; mod doctor; mod guard; +#[cfg(test)] +mod hazards_tests; mod impact; mod markdown; mod measurement; @@ -54,7 +57,7 @@ pub use diff::{BaseCommit, DiffReport, DiffReportOptions, Head, HeadCommit}; pub use doctor::{DoctorCheck, DoctorReport, DoctorStatus, DoctorSummary}; pub use guard::{GuardAllowedTarget, GuardDeniedTarget, GuardReport}; pub use impact::{ChangedBase, ImpactReport}; -pub use measurement::CommitMeasurement; +pub use measurement::{CommitMeasurement, CommitMeasurementOptions}; pub use ownership::OwnershipOptions; pub use report_schema::report_schema; pub use saved::{SavedReport, SavedReportError}; @@ -102,6 +105,10 @@ pub struct Report { #[serde(default, skip_serializing_if = "Vec::is_empty")] skipped: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] + rejected_statements: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + sql_schemas: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] declaration_only: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] submodules: Vec, @@ -109,6 +116,31 @@ pub struct Report { over_budget: Vec, } +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RejectedStatementEntry { + pub path: String, + pub line: u32, + pub dialect: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SqlSchemaSummary { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub package: Option, + pub dialect: String, + pub tables: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct HazardLineRow { + pub id: String, + pub path: String, + pub line: u32, + pub rule: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub owners: Vec, +} + #[derive(Debug, Serialize, Deserialize)] pub struct BudgetFailure { #[serde(default, skip_serializing_if = "Option::is_none")] @@ -278,12 +310,23 @@ struct SourceSetSection { orphan_files: Option, #[serde(default, skip_serializing_if = "Option::is_none")] test_gap: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + hazards: Option, #[serde(default, flatten)] external_metrics: BTreeMap, #[serde(default, skip_serializing_if = "Vec::is_empty")] packages: Vec, } +#[derive(Debug, Serialize, Deserialize)] +struct HazardsSection { + ratio: Decimal, + hazard_lines: u64, + source_lines: u64, + #[serde(flatten)] + findings: Findings, +} + #[derive(Debug, Serialize, Deserialize)] struct TestGapSection { ratio: Decimal, @@ -414,6 +457,15 @@ struct PackageSection { import_cycles: Option, #[serde(default, skip_serializing_if = "Option::is_none")] test_gap: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + hazards: Option, +} + +#[derive(Debug, Serialize, Deserialize)] +struct PackageHazards { + ratio: Decimal, + hazard_lines: u64, + source_lines: u64, } #[derive(Debug, Serialize, Deserialize)] @@ -874,6 +926,7 @@ impl_single_path_owner!(ExternalMetricFinding, path); impl_single_path_owner!(BoundaryFindingRow, importer); impl_single_path_owner!(OrphanFileRow, path); impl_single_path_owner!(TestGapFindingRow, path); +impl_single_path_owner!(HazardLineRow, path); impl OwnedFinding for CloneGroupFinding { fn assign_owners(&mut self, codeowners: &Codeowners) { @@ -927,6 +980,10 @@ impl FindingKind for TestGapFindingRow { const LIST_KEY: &'static str = "findings"; } +impl FindingKind for HazardLineRow { + const LIST_KEY: &'static str = "findings"; +} + impl DependenciesSection { fn from_hygiene( hygiene: &DependencyHygiene, @@ -1148,6 +1205,36 @@ impl From<&TestGapFinding> for TestGapFindingRow { } } +macro_rules! impl_line_rule_row { + ($from:ty, $to:ident) => { + impl From<&$from> for $to { + fn from(finding: &$from) -> $to { + $to { + id: finding.id.to_string(), + path: finding.path.to_string(), + line: finding.line, + rule: finding.rule.clone(), + owners: Vec::new(), + } + } + } + }; +} + +impl_line_rule_row!(FlaggedLineFinding, FlaggedLineRow); +impl_line_rule_row!(HazardLineFinding, HazardLineRow); + +impl HazardsSection { + fn new(hazards: &Hazards, view: FindingsView<'_>) -> HazardsSection { + HazardsSection { + ratio: Decimal::rounded(hazards.ratio()), + hazard_lines: hazards.hazard_lines(), + source_lines: hazards.source_lines(), + findings: view.map(hazards.findings()), + } + } +} + #[derive(Clone, Copy)] struct SectionOptions<'a> { findings: FindingsShown, @@ -1157,35 +1244,35 @@ struct SectionOptions<'a> { orphan_files: Option<&'a OrphanFiles>, ownership: OwnershipOptions<'a>, has_imports: bool, + has_hazard_rules: bool, + disabled_hazard_rules: &'a BTreeSet, coverage_reports_named: bool, per_language_section: bool, } +#[derive(Clone, Copy)] +struct SectionModels<'a> { + model: &'a CodeModel, + import_model: Option<&'a CodeModel>, + coverage_model: Option<&'a CodeModel>, + hazards_model: Option<&'a CodeModel>, +} + impl SourceSetSections { fn new( source_sets: &SourceSets, import_source_sets: Option<&SourceSets>, coverage_source_sets: Option<&SourceSets>, + hazards_source_sets: Option<&SourceSets>, ranges: &ReferenceRangeScope, options: SectionOptions<'_>, ) -> Result { let mut sections = SourceSetSections::default(); for (source_set, model) in source_sets.iter() { if !model.files.is_empty() { - let import_model = import_source_sets - .map(|sets| sets.get(source_set)) - .filter(|imports| !imports.files.is_empty()); - let coverage_model = if source_set == SourceSet::Production { - match coverage_source_sets { - Some(sets) => { - let prod = sets.get(SourceSet::Production); - (!prod.files.is_empty()).then_some(prod) - } - None => Some(model), - } - } else { - None - }; + let import_model = select_non_empty(import_source_sets, source_set); + let coverage_model = select_coverage_model(source_set, model, coverage_source_sets); + let hazards_model = select_non_empty(hazards_source_sets, source_set); let source_set_options = SectionOptions { boundaries: options.boundaries.filter(|config| { import_model.is_some() && config.applies_to_source_set(source_set) @@ -1196,9 +1283,12 @@ impl SourceSetSections { ..options }; *sections.slot(source_set) = Some(SourceSetSection::new( - model, - import_model, - coverage_model, + SectionModels { + model, + import_model, + coverage_model, + hazards_model, + }, ranges, source_set_options, )?); @@ -1259,6 +1349,12 @@ impl SourceSetSections { .iter() .map(move |test_gap| (source_set, TEST_GAP_METRIC_KEY, test_gap.ratio.0)), ) + .chain( + section + .hazards + .iter() + .map(move |hazards| (source_set, HAZARDS_METRIC_KEY, hazards.ratio.0)), + ) .chain( section.external_metrics.iter().map(move |(key, metric)| { (source_set, key.as_str(), metric.header.ratio.0) @@ -1269,29 +1365,53 @@ impl SourceSetSections { } } +fn select_non_empty(source_sets: Option<&SourceSets>, source_set: SourceSet) -> Option<&CodeModel> { + source_sets + .map(|sets| sets.get(source_set)) + .filter(|model| !model.files.is_empty()) +} + +fn select_coverage_model<'a>( + source_set: SourceSet, + model: &'a CodeModel, + coverage_source_sets: Option<&'a SourceSets>, +) -> Option<&'a CodeModel> { + if source_set != SourceSet::Production { + return None; + } + match coverage_source_sets { + Some(sets) => select_non_empty(Some(sets), SourceSet::Production), + None => Some(model), + } +} + impl SourceSetSection { - fn new<'a>( - model: &'a CodeModel, - import_model: Option<&'a CodeModel>, - coverage_model: Option<&'a CodeModel>, + fn new( + models: SectionModels<'_>, ranges: &ReferenceRangeScope, options: SectionOptions<'_>, ) -> Result { + let model = models.model; let view = FindingsView { shown: options.findings, ownership: options.ownership, }; - let effective_import_model = import_model.filter(|_| options.has_imports); + let effective_import_model = models.import_model.filter(|_| options.has_imports); + let effective_hazards_model = models.hazards_model.filter(|_| options.has_hazard_rules); let boundaries_config = effective_import_model .is_some() .then_some(options.boundaries) .flatten(); let measured = Measured::new( - model, - effective_import_model, - coverage_model, + SectionModels { + model, + import_model: effective_import_model, + coverage_model: models.coverage_model, + hazards_model: effective_hazards_model, + }, boundaries_config, options.duplication, + options.disabled_hazard_rules, ); let boundaries = measured .boundaries @@ -1306,6 +1426,10 @@ impl SourceSetSection { .test_gap .as_ref() .map(|evaluated| TestGapSection::new(evaluated, view)); + let hazards = measured + .hazards + .as_ref() + .map(|evaluated| HazardsSection::new(evaluated, view)); let mut external_metrics = BTreeMap::new(); for plugin in options.metric_plugins { let result = plugin.measure(model)?; @@ -1397,8 +1521,17 @@ impl SourceSetSection { boundaries, orphan_files, test_gap, + hazards, external_metrics, - packages: package_sections(model, effective_import_model, coverage_model, &measured), + packages: package_sections( + SectionModels { + model, + import_model: effective_import_model, + coverage_model: models.coverage_model, + hazards_model: effective_hazards_model, + }, + &measured, + ), }) } } @@ -1556,18 +1689,6 @@ impl CloneLocation { } } -impl From<&FlaggedLineFinding> for FlaggedLineRow { - fn from(finding: &FlaggedLineFinding) -> FlaggedLineRow { - FlaggedLineRow { - id: finding.id.to_string(), - path: finding.path.to_string(), - line: finding.line, - rule: finding.rule.clone(), - owners: Vec::new(), - } - } -} - impl ImportCycleFinding { fn new(cycle: &ImportCycle) -> ImportCycleFinding { ImportCycleFinding { @@ -1616,16 +1737,17 @@ struct Measured { import_cycles: Option, boundaries: Option, test_gap: Option, + hazards: Option, } impl Measured { fn new( - model: &CodeModel, - import_model: Option<&CodeModel>, - coverage_model: Option<&CodeModel>, + models: SectionModels<'_>, boundaries: Option<&BoundariesConfig>, duplication_config: DuplicationConfig, + disabled_hazard_rules: &BTreeSet, ) -> Measured { + let model = models.model; let near_clones = duplication_config.near_clones.then(|| { NearCloneConfig::new(duplication_config.min_similarity.ratio()) .expect("validated min_similarity is in (0, 1]") @@ -1636,11 +1758,14 @@ impl Measured { MinimumDistinctTokens::DEFAULT, near_clones, ); - let import_cycles = import_model.map(ImportCycles::measure); - let boundaries = import_model.and_then(|imports| { + let import_cycles = models.import_model.map(ImportCycles::measure); + let boundaries = models.import_model.and_then(|imports| { boundaries.map(|config| Boundaries::measure(imports, &ConfigBoundaryPolicy(config))) }); - let test_gap = coverage_model.and_then(TestGap::measure); + let test_gap = models.coverage_model.and_then(TestGap::measure); + let hazards = models + .hazards_model + .and_then(|hazards_model| Hazards::measure(hazards_model, disabled_hazard_rules)); Measured { erosion: Erosion::measure(model), cognitive_complexity: CognitiveComplexity::measure(model), @@ -1649,16 +1774,13 @@ impl Measured { import_cycles, boundaries, test_gap, + hazards, } } } -fn package_sections<'a>( - model: &'a CodeModel, - import_model: Option<&'a CodeModel>, - coverage_model: Option<&'a CodeModel>, - measured: &Measured, -) -> Vec { +fn package_sections<'a>(models: SectionModels<'a>, measured: &Measured) -> Vec { + let model = models.model; if !model.workspace.has_members() { return Vec::new(); } @@ -1671,12 +1793,18 @@ fn package_sections<'a>( let mut cognitive = measured.cognitive_complexity.by_package(model); let mut duplication = measured.duplication.by_package(model); let mut verbosity = measured.verbosity.by_package(model); - let mut import_cycles = import_model + let mut import_cycles = models + .import_model .zip(measured.import_cycles.as_ref()) .map(|(imports, cycles)| cycles.by_package(imports)); - let mut test_gap = coverage_model + let mut test_gap = models + .coverage_model .zip(measured.test_gap.as_ref()) .map(|(coverage, gap)| gap.by_package(coverage)); + let mut hazards = models + .hazards_model + .zip(measured.hazards.as_ref()) + .map(|(hazards_model, hazards)| hazards.by_package(hazards_model)); measured .erosion .by_package(model) @@ -1701,6 +1829,13 @@ fn package_sections<'a>( total_function_mass: Decimal::rounded(gap.total), }) }); + let package_hazards = hazards.as_mut().and_then(|by_package| { + by_package.remove(&package).map(|lines| PackageHazards { + ratio: Decimal::rounded(lines.ratio()), + hazard_lines: lines.hazard_lines, + source_lines: lines.source_lines, + }) + }); PackageSection { path: package.to_string(), files: package_files, @@ -1725,6 +1860,7 @@ fn package_sections<'a>( }, import_cycles: package_import_cycles, test_gap: package_test_gap, + hazards: package_hazards, } }) .collect() @@ -1746,17 +1882,49 @@ pub struct ReportOptions<'a> { pub unmatched_coverage_paths: &'a [String], } +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ReportExtras { + pub disabled_hazard_rules: BTreeSet, + pub rejected_statements: Vec, + pub sql_schemas: Vec, +} + +impl ReportExtras { + pub fn with_disabled_hazard_rules(mut self, rules: BTreeSet) -> ReportExtras { + self.disabled_hazard_rules = rules; + self + } + + pub fn with_rejected_statements( + mut self, + rejected_statements: Vec, + ) -> ReportExtras { + self.rejected_statements = rejected_statements; + self + } + + pub fn with_sql_schemas(mut self, sql_schemas: Vec) -> ReportExtras { + self.sql_schemas = sql_schemas; + self + } +} + +struct MeasuredSectionModels { + model: CodeModel, + import_model: Option, + coverage_model: Option, + hazards_model: Option, +} + impl MeasuredSection { fn new( - model: CodeModel, - import_model: Option, - coverage_model: Option, + models: MeasuredSectionModels, hygiene: &DependencyHygiene, ranges: &ReferenceRangeScope, options: SectionOptions<'_>, ) -> Result { - let files = model.files.len(); - let lines = source_lines(&model); + let files = models.model.files.len(); + let lines = source_lines(&models.model); let view = FindingsView { shown: options.findings, ownership: options.ownership, @@ -1775,18 +1943,29 @@ impl MeasuredSection { ..options } }; - let source_sets = model.into_source_sets(); - let separate_import_source_sets = import_model.map(CodeModel::into_source_sets); + let source_sets = models.model.into_source_sets(); + let separate_import_source_sets = models.import_model.map(CodeModel::into_source_sets); let import_source_sets = if options.has_imports { Some(separate_import_source_sets.as_ref().unwrap_or(&source_sets)) } else { None }; - let separate_coverage_source_sets = coverage_model.map(CodeModel::into_source_sets); + let separate_coverage_source_sets = models.coverage_model.map(CodeModel::into_source_sets); + let separate_hazards_source_sets = models.hazards_model.map(CodeModel::into_source_sets); + let hazards_source_sets = if options.has_hazard_rules { + Some( + separate_hazards_source_sets + .as_ref() + .unwrap_or(&source_sets), + ) + } else { + None + }; let source_sets = SourceSetSections::new( &source_sets, import_source_sets, separate_coverage_source_sets.as_ref(), + hazards_source_sets, ranges, section_options, )?; @@ -1941,6 +2120,15 @@ impl Report { languages: Vec, submodules: Vec, options: ReportOptions<'_>, + ) -> Result { + Report::summarize_with_extras(languages, submodules, options, ReportExtras::default()) + } + + pub fn summarize_with_extras( + languages: Vec, + submodules: Vec, + options: ReportOptions<'_>, + extras: ReportExtras, ) -> Result { let ignored = options.dependencies.ignored(); let measured_total_hygiene; @@ -1956,6 +2144,9 @@ impl Report { .partition(|language| !language.model.files.is_empty()); let top_has_imports = measured.is_empty() || measured.iter().any(|language| language.has_imports); + let top_has_hazard_rules = measured + .iter() + .any(|language| model_has_hazard_rules(&language.model)); let section_options = SectionOptions { findings: options.findings, metric_plugins: options.metric_plugins, @@ -1964,6 +2155,8 @@ impl Report { orphan_files: options.orphan_files, ownership: options.ownership, has_imports: top_has_imports, + has_hazard_rules: top_has_hazard_rules, + disabled_hazard_rules: &extras.disabled_hazard_rules, coverage_reports_named: options.coverage_reports_named, per_language_section: false, }; @@ -1971,6 +2164,7 @@ impl Report { build_per_language_sections(&measured, &options, ignored, section_options)?; let import_bearing_model = collect_import_bearing_model(&measured, top_has_imports); let coverage_bearing_model = collect_coverage_bearing_model(&measured); + let hazards_bearing_model = collect_hazards_bearing_model(&measured, top_has_hazard_rules); let model = CodeModel::merge( measured .into_iter() @@ -1984,9 +2178,12 @@ impl Report { .map(RepoPath::to_string) .collect(); let measured = MeasuredSection::new( - model, - import_bearing_model, - coverage_bearing_model, + MeasuredSectionModels { + model, + import_model: import_bearing_model, + coverage_model: coverage_bearing_model, + hazards_model: hazards_bearing_model, + }, total_hygiene, &total_ranges, section_options, @@ -1998,6 +2195,8 @@ impl Report { Ok(Report { over_budget: failures, skipped, + rejected_statements: extras.rejected_statements, + sql_schemas: extras.sql_schemas, declaration_only, submodules: submodules.iter().map(RepoPath::to_string).collect(), measured, @@ -2083,6 +2282,27 @@ fn format_unmatched_coverage_note(paths: &[String]) -> Option { } } +pub(crate) fn model_has_hazard_rules(model: &CodeModel) -> bool { + model.languages.iter().any(|facts| facts.has_hazard_rules) +} + +fn collect_hazards_bearing_model( + measured: &[MeasuredLanguage], + any_has_hazard_rules: bool, +) -> Option { + let all_measured_have_hazard_rules = measured + .iter() + .all(|language| model_has_hazard_rules(&language.model)); + (any_has_hazard_rules && !all_measured_have_hazard_rules).then(|| { + CodeModel::merge( + measured + .iter() + .filter(|language| model_has_hazard_rules(&language.model)) + .map(|language| language.model.clone()), + ) + }) +} + fn collect_import_bearing_model( measured: &[MeasuredLanguage], top_has_imports: bool, @@ -2155,15 +2375,20 @@ fn build_single_language_section( .and_then(|map| map.get(&language.plugin)) }) .flatten(); + let language_has_hazard_rules = model_has_hazard_rules(&language.model); MeasuredSection::new( - language.model.clone(), - None, - None, + MeasuredSectionModels { + model: language.model.clone(), + import_model: None, + coverage_model: None, + hazards_model: None, + }, language_hygiene, &ReferenceRangeScope::OneLanguage(language.reference_ranges.clone()), SectionOptions { orphan_files: language_orphans, has_imports: language.has_imports, + has_hazard_rules: language_has_hazard_rules, per_language_section: true, ..section_options }, diff --git a/crates/report/src/markdown.rs b/crates/report/src/markdown.rs index 0a6f03e3..4d0244fd 100644 --- a/crates/report/src/markdown.rs +++ b/crates/report/src/markdown.rs @@ -2,9 +2,10 @@ use crate::ownership::OwnedFinding; use crate::{ BoundaryFindingRow, CloneFamilyFinding, CloneGroupFinding, CloneLocation, CognitiveComplexityFinding, DependenciesSection, ErodedFunctionFinding, ExternalMetricFinding, - Findings, FlaggedLineRow, ImportCycleFinding, ImportCyclesSection, ImportedDependencyRow, - MeasuredSection, MetricHeader, OrphanFileRow, PackageSection, ReferenceRangeEntry, Report, - SourceSetSection, TestGapFindingRow, UnresolvedImportRow, UnusedDependencyRow, + Findings, FlaggedLineRow, HazardLineRow, HazardsSection, ImportCycleFinding, + ImportCyclesSection, ImportedDependencyRow, MeasuredSection, MetricHeader, OrphanFileRow, + PackageSection, ReferenceRangeEntry, RejectedStatementEntry, Report, SourceSetSection, + SqlSchemaSummary, TestGapFindingRow, UnresolvedImportRow, UnusedDependencyRow, }; #[cfg(test)] @@ -37,6 +38,8 @@ const PACKAGE_COLUMNS: [&str; 8] = [ "Verbosity", ]; pub(crate) const FLAGGED_LINE_COLUMNS: [&str; 2] = ["Flagged line", "Rule"]; +pub(crate) const HAZARD_LINE_COLUMNS: [&str; 3] = ["Path", "Line", "Rule"]; +const SQL_SCHEMA_COLUMNS: [&str; 3] = ["Scope", "Dialect", "Tables"]; pub(crate) const EXTERNAL_FINDING_COLUMNS: [&str; 2] = ["Location", "Message"]; pub(crate) const BOUNDARY_FINDING_COLUMNS: [&str; 6] = [ "Importer", @@ -80,6 +83,10 @@ pub(crate) const FLAGGED_LINE: Noun = Noun { one: "Flagged line", many: "Flagged lines", }; +pub(crate) const HAZARD_LINE: Noun = Noun { + one: "Hazard line", + many: "Hazard lines", +}; const MODULE: Noun = Noun { one: "module", many: "modules", @@ -167,8 +174,10 @@ pub(crate) fn render(report: &Report) -> String { blocks.push(packages); } push_language_sections(&mut blocks, &report.languages); + push_sql_schemas(&mut blocks, &report.sql_schemas); push_source_set_findings(&mut blocks, §ions); push_dependency_findings(&mut blocks, report.measured.dependencies.as_ref()); + push_rejected_statements(&mut blocks, &report.rejected_statements); let not_measured = files_not_measured(report); if !not_measured.is_empty() { blocks.push("## Files not measured".to_string()); @@ -177,6 +186,39 @@ pub(crate) fn render(report: &Report) -> String { blocks.join("\n\n") } +fn push_sql_schemas(blocks: &mut Vec, schemas: &[SqlSchemaSummary]) { + if schemas.is_empty() { + return; + } + blocks.push("## SQL schemas".to_string()); + blocks.push(table( + &SQL_SCHEMA_COLUMNS, + schemas.iter().map(sql_schema_row).collect(), + )); +} + +fn sql_schema_row(schema: &SqlSchemaSummary) -> Vec { + let scope = match schema.package.as_deref() { + Some(package) => code(package), + None => "root".to_string(), + }; + vec![scope, code(&schema.dialect), schema.tables.to_string()] +} + +fn push_rejected_statements(blocks: &mut Vec, rejected: &[RejectedStatementEntry]) { + if rejected.is_empty() { + return; + } + blocks.push("## Rejected statements".to_string()); + blocks.push(list(rejected.iter().map(|entry| { + format!( + "{}: dialect {}", + code(&format!("{}:{}", entry.path, entry.line)), + code(&entry.dialect) + ) + }))); +} + fn push_dependencies_summary(blocks: &mut Vec, dependencies: Option<&DependenciesSection>) { if let Some(dependencies) = dependencies { blocks.push("## Dependencies".to_string()); @@ -239,38 +281,55 @@ fn metric_table(sections: &[(&str, &SourceSetSection)]) -> Option { )) } +struct OptionalPackageColumns { + import_cycles: bool, + test_gap: bool, + hazards: bool, +} + fn package_table(sections: &[(&str, &SourceSetSection)]) -> Option { - let show_import_cycles = sections.iter().any(|(_, section)| { - section - .packages - .iter() - .any(|package| package.import_cycles.is_some()) - }); - let show_test_gap = sections.iter().any(|(_, section)| { - section - .packages - .iter() - .any(|package| package.test_gap.is_some()) - }); + let optional = OptionalPackageColumns { + import_cycles: sections.iter().any(|(_, section)| { + section + .packages + .iter() + .any(|package| package.import_cycles.is_some()) + }), + test_gap: sections.iter().any(|(_, section)| { + section + .packages + .iter() + .any(|package| package.test_gap.is_some()) + }), + hazards: sections.iter().any(|(_, section)| { + section + .packages + .iter() + .any(|package| package.hazards.is_some()) + }), + }; let package_rows: Vec> = sections .iter() .flat_map(|(name, section)| { section .packages .iter() - .map(|package| package_row(name, package, show_import_cycles, show_test_gap)) + .map(|package| package_row(name, package, &optional)) }) .collect(); if package_rows.is_empty() { return None; } let mut columns: Vec<&str> = PACKAGE_COLUMNS.to_vec(); - if show_import_cycles { + if optional.import_cycles { columns.push("Import cycles"); } - if show_test_gap { + if optional.test_gap { columns.push("Test gap"); } + if optional.hazards { + columns.push("Hazards"); + } Some(table(&columns, package_rows)) } @@ -287,8 +346,7 @@ pub(crate) fn sentence_item(failure: &impl std::fmt::Display) -> String { fn package_row( source_set: &str, package: &PackageSection, - show_import_cycles: bool, - show_test_gap: bool, + optional: &OptionalPackageColumns, ) -> Vec { let mut cells = vec![ source_set.to_string(), @@ -300,13 +358,13 @@ fn package_row( package.duplication.ratio.0.to_string(), package.verbosity.ratio.0.to_string(), ]; - if show_import_cycles { + if optional.import_cycles { cells.push(package.import_cycles.as_ref().map_or_else( || "not measured".to_string(), |cycles| cycles.ratio.0.to_string(), )); } - if show_test_gap { + if optional.test_gap { cells.push( package .test_gap @@ -314,6 +372,12 @@ fn package_row( .map_or_else(|| "not measured".to_string(), |gap| gap.ratio.0.to_string()), ); } + if optional.hazards { + cells.push(package.hazards.as_ref().map_or_else( + || "not measured".to_string(), + |hazards| hazards.ratio.0.to_string(), + )); + } cells } @@ -455,6 +519,9 @@ fn metric_rows(source_set: &str, section: &SourceSetSection) -> Vec> "no published Reference range".to_string(), ]); } + if let Some(hazards) = §ion.hazards { + rows.push(hazards_metric_row(source_set, hazards)); + } for external in section.external_metrics.values() { rows.push(row( &external.name, @@ -465,6 +532,19 @@ fn metric_rows(source_set: &str, section: &SourceSetSection) -> Vec> rows } +fn hazards_metric_row(source_set: &str, hazards: &HazardsSection) -> Vec { + vec![ + source_set.to_string(), + "Hazards".to_string(), + hazards.ratio.0.to_string(), + format!( + "{} of {} Hazard lines", + hazards.hazard_lines, hazards.source_lines + ), + "not applicable".to_string(), + ] +} + fn import_cycles_behind_the_value(section: &ImportCyclesSection) -> String { let modules = section.modules as u64; let in_cycles = format!( @@ -570,6 +650,15 @@ fn findings_blocks(section: &SourceSetSection) -> Vec { |listed| findings_table(&TEST_GAP_COLUMNS, listed, test_gap_row), ); } + if let Some(hazards) = §ion.hazards { + push_findings( + &mut blocks, + "Hazards", + &hazards.findings, + &HAZARD_LINE, + |listed| findings_table(&HAZARD_LINE_COLUMNS, listed, hazard_line_row), + ); + } for external in section.external_metrics.values() { push_findings( &mut blocks, @@ -728,6 +817,10 @@ pub(crate) fn flagged_line_row(row: &FlaggedLineRow) -> Vec { ] } +pub(crate) fn hazard_line_row(row: &HazardLineRow) -> Vec { + vec![code(&row.path), row.line.to_string(), prose(&row.rule)] +} + pub(crate) fn external_finding_row(finding: &ExternalMetricFinding) -> Vec { let location = match finding.end_line { Some(end_line) if end_line != finding.line => { diff --git a/crates/report/src/measurement.rs b/crates/report/src/measurement.rs index 2844c9a9..b51dc7fc 100644 --- a/crates/report/src/measurement.rs +++ b/crates/report/src/measurement.rs @@ -7,8 +7,9 @@ use serde::{Deserialize, Serialize}; use crate::{ BoundaryFindingRow, CloneFamilyFinding, CloneGroupFinding, CognitiveComplexityFinding, - ErodedFunctionFinding, ExternalMetricFinding, FlaggedLineRow, ImportCycleFinding, - ImportedDependencyRow, Measured, OrphanFileRow, UnusedDependencyRow, + ErodedFunctionFinding, ExternalMetricFinding, FlaggedLineRow, HazardLineRow, + ImportCycleFinding, ImportedDependencyRow, Measured, OrphanFileRow, SectionModels, + UnusedDependencyRow, model_has_hazard_rules, }; #[derive(Debug, Serialize, Deserialize)] @@ -43,10 +44,23 @@ pub(crate) struct SourceSetMeasurement { pub(crate) boundaries: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) orphan_files: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) hazards: Option>, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub(crate) external_metrics: BTreeMap, } +#[derive(Clone, Copy)] +pub struct CommitMeasurementOptions<'a> { + pub metric_plugins: &'a [&'a dyn MetricPlugin], + pub boundaries: Option<&'a BoundariesConfig>, + pub dependencies: &'a DependenciesConfig, + pub duplication: DuplicationConfig, + pub orphan_files: Option<&'a OrphanFiles>, + pub dependency_hygiene: Option<&'a DependencyHygiene>, + pub disabled_hazard_rules: &'a BTreeSet, +} + #[derive(Debug, Serialize, Deserialize)] pub(crate) struct ExternalMetricCommitMeasurement { pub(crate) name: String, @@ -133,9 +147,28 @@ impl CommitMeasurement { orphan_files: Option<&OrphanFiles>, dependency_hygiene: Option<&DependencyHygiene>, ) -> Result { - let ignored = dependencies_config.ignored(); + let disabled_hazard_rules = BTreeSet::new(); + CommitMeasurement::of_languages_with_full_options( + languages, + CommitMeasurementOptions { + metric_plugins, + boundaries, + dependencies: dependencies_config, + duplication, + orphan_files, + dependency_hygiene, + disabled_hazard_rules: &disabled_hazard_rules, + }, + ) + } + + pub fn of_languages_with_full_options( + languages: Vec, + options: CommitMeasurementOptions<'_>, + ) -> Result { + let ignored = options.dependencies.ignored(); let measured_hygiene; - let hygiene = match dependency_hygiene { + let hygiene = match options.dependency_hygiene { Some(precomputed) => precomputed, None => { measured_hygiene = measure_commit_hygiene(&languages, ignored); @@ -149,31 +182,46 @@ impl CommitMeasurement { let any_has_imports = measured.is_empty() || measured.iter().copied().any(model_has_imports); let all_have_imports = measured.iter().copied().all(model_has_imports); - let separate_import_source_sets = - (any_has_imports && !all_have_imports).then(|| build_import_source_sets(&languages)); + let separate_import_source_sets = (any_has_imports && !all_have_imports) + .then(|| build_filtered_source_sets(&languages, model_has_imports)); + let any_has_hazard_rules = measured.iter().copied().any(model_has_hazard_rules); + let all_have_hazard_rules = + !measured.is_empty() && measured.iter().copied().all(model_has_hazard_rules); + let separate_hazards_source_sets = (any_has_hazard_rules && !all_have_hazard_rules) + .then(|| build_filtered_source_sets(&languages, model_has_hazard_rules)); let dependencies = any_has_imports .then(|| DependenciesMeasurement::from_hygiene(hygiene)) .flatten(); let source_sets = CodeModel::merge(languages).into_source_sets(); let measure = |source_set: SourceSet, set_orphans: Option<&OrphanFiles>| { - let import_model = select_import_model( + let import_model = select_subset_model( source_set, any_has_imports, &source_sets, separate_import_source_sets.as_ref(), + false, + ); + let hazards_model = select_subset_model( + source_set, + any_has_hazard_rules, + &source_sets, + separate_hazards_source_sets.as_ref(), + true, ); measure_source_set( source_set, - source_sets.get(source_set), - import_model, - metric_plugins, - boundaries, - duplication, + SectionModels { + model: source_sets.get(source_set), + import_model, + coverage_model: None, + hazards_model, + }, + options, set_orphans, ) }; Ok(CommitMeasurement { - production: measure(SourceSet::Production, orphan_files)?, + production: measure(SourceSet::Production, options.orphan_files)?, test: measure(SourceSet::Test, None)?, generated: measure(SourceSet::Generated, None)?, vendored: measure(SourceSet::Vendored, None)?, @@ -242,22 +290,34 @@ fn model_has_imports(model: &CodeModel) -> bool { impl SourceSetMeasurement { fn of( - model: &CodeModel, - import_model: Option<&CodeModel>, - metric_plugins: &[&dyn MetricPlugin], + models: SectionModels<'_>, boundaries: Option<&BoundariesConfig>, - duplication_config: DuplicationConfig, + options: CommitMeasurementOptions<'_>, orphan_files: Option<&OrphanFiles>, ) -> Result { - let measured = Measured::new(model, import_model, None, boundaries, duplication_config); + let model = models.model; + let measured = Measured::new( + models, + boundaries, + options.duplication, + options.disabled_hazard_rules, + ); let boundaries = measured .boundaries .as_ref() .map(|evaluated| finding_measurement(evaluated.ratio(), evaluated.findings())); let orphan_files = orphan_files .map(|evaluated| finding_measurement(evaluated.ratio(), evaluated.findings())); + let hazards = measured.hazards.as_ref().map(|evaluated| { + MetricMeasurement::from_items( + evaluated.ratio(), + evaluated.hazard_lines() as f64, + evaluated.findings(), + HazardLineRow::from, + ) + }); let mut external_metrics = BTreeMap::new(); - for plugin in metric_plugins { + for plugin in options.metric_plugins { let result = plugin.measure(model)?; external_metrics.insert( plugin.key().to_owned(), @@ -318,6 +378,7 @@ impl SourceSetMeasurement { }), boundaries, orphan_files, + hazards, external_metrics, }) } @@ -358,27 +419,34 @@ fn measure_commit_hygiene( DependencyHygiene::merge(measured) } -fn build_import_source_sets(languages: &[CodeModel]) -> SourceSets { +fn build_filtered_source_sets( + languages: &[CodeModel], + predicate: fn(&CodeModel) -> bool, +) -> SourceSets { let mut models = Vec::new(); for model in languages { - if !model.files.is_empty() && model_has_imports(model) { + if !model.files.is_empty() && predicate(model) { models.push(model.clone()); } } CodeModel::merge(models).into_source_sets() } -fn select_import_model<'a>( +fn select_subset_model<'a>( source_set: SourceSet, - any_has_imports: bool, + enabled: bool, source_sets: &'a SourceSets, - separate_import_source_sets: Option<&'a SourceSets>, + separate_source_sets: Option<&'a SourceSets>, + require_non_empty_shared: bool, ) -> Option<&'a CodeModel> { - if !any_has_imports { + if !enabled { return None; } - match separate_import_source_sets { - None => Some(source_sets.get(source_set)), + match separate_source_sets { + None => { + let candidate = source_sets.get(source_set); + (!require_non_empty_shared || !candidate.files.is_empty()).then_some(candidate) + } Some(sets) => { let candidate = sets.get(source_set); (!candidate.files.is_empty()).then_some(candidate) @@ -388,22 +456,13 @@ fn select_import_model<'a>( fn measure_source_set( source_set: SourceSet, - model: &CodeModel, - import_model: Option<&CodeModel>, - metric_plugins: &[&dyn MetricPlugin], - boundaries: Option<&BoundariesConfig>, - duplication: DuplicationConfig, + models: SectionModels<'_>, + options: CommitMeasurementOptions<'_>, orphan_files: Option<&OrphanFiles>, ) -> Result { - let applicable_boundaries = boundaries - .filter(|config| import_model.is_some() && config.applies_to_source_set(source_set)); - let applicable_orphans = orphan_files.filter(|_| import_model.is_some()); - SourceSetMeasurement::of( - model, - import_model, - metric_plugins, - applicable_boundaries, - duplication, - applicable_orphans, - ) + let applicable_boundaries = options + .boundaries + .filter(|config| models.import_model.is_some() && config.applies_to_source_set(source_set)); + let applicable_orphans = orphan_files.filter(|_| models.import_model.is_some()); + SourceSetMeasurement::of(models, applicable_boundaries, options, applicable_orphans) } diff --git a/crates/report/src/report_schema.rs b/crates/report/src/report_schema.rs index 41456feb..965a4980 100644 --- a/crates/report/src/report_schema.rs +++ b/crates/report/src/report_schema.rs @@ -41,6 +41,16 @@ fn report_schema_value() -> Value { } } }, + "rejected_statements": { + "type": "array", + "description": "Statements that a Language plugin's parser could not parse; they still count in token Metrics and receive no statement rules.", + "items": { "$ref": "#/$defs/RejectedStatementEntry" } + }, + "sql_schemas": { + "type": "array", + "description": "Table counts of each SQL schema built per Workspace package (or repository root) and Dialect.", + "items": { "$ref": "#/$defs/SqlSchemaSummary" } + }, "declaration_only": { "type": "array", "items": { "type": "string" } }, "submodules": { "type": "array", "items": { "type": "string" } }, "over_budget": { @@ -85,6 +95,7 @@ fn report_schema_value() -> Value { "boundaries": { "type": "object" }, "orphan_files": { "type": "object" }, "test_gap": { "$ref": "#/$defs/TestGapSection" }, + "hazards": { "$ref": "#/$defs/HazardsSection" }, "packages": { "type": "array", "items": { "$ref": "#/$defs/PackageSection" } @@ -104,6 +115,7 @@ fn report_schema_value() -> Value { "import_cycles": { "type": "object" }, "boundaries": { "type": "object" }, "test_gap": false, + "hazards": { "$ref": "#/$defs/HazardsSection" }, "packages": { "type": "array", "items": { "$ref": "#/$defs/PackageSection" } @@ -154,7 +166,8 @@ fn report_schema_value() -> Value { "duplication": { "type": "object" }, "verbosity": { "type": "object" }, "import_cycles": { "type": "object" }, - "test_gap": { "$ref": "#/$defs/PackageTestGap" } + "test_gap": { "$ref": "#/$defs/PackageTestGap" }, + "hazards": { "$ref": "#/$defs/PackageHazards" } }, "additionalProperties": false }, @@ -168,6 +181,64 @@ fn report_schema_value() -> Value { }, "additionalProperties": false }, + "HazardsSection": { + "type": "object", + "description": "Hazards for this Source set; omitted when no measured language has Hazard line rules.", + "required": ["ratio", "hazard_lines", "source_lines", "findings"], + "properties": { + "ratio": { "type": "number", "minimum": 0, "maximum": 1 }, + "hazard_lines": { "type": "integer", "minimum": 0 }, + "source_lines": { "type": "integer", "minimum": 0 }, + "findings": { + "type": "array", + "items": { "$ref": "#/$defs/HazardLineFinding" } + }, + "findings_left_out": { "type": "integer", "minimum": 1 } + }, + "additionalProperties": false + }, + "HazardLineFinding": { + "type": "object", + "required": ["id", "path", "line", "rule"], + "properties": { + "id": { "type": "string" }, + "path": { "type": "string" }, + "line": { "type": "integer", "minimum": 1 }, + "rule": { "type": "string" }, + "owners": { "type": "array", "items": { "type": "string" } } + }, + "additionalProperties": false + }, + "PackageHazards": { + "type": "object", + "required": ["ratio", "hazard_lines", "source_lines"], + "properties": { + "ratio": { "type": "number", "minimum": 0, "maximum": 1 }, + "hazard_lines": { "type": "integer", "minimum": 0 }, + "source_lines": { "type": "integer", "minimum": 0 } + }, + "additionalProperties": false + }, + "RejectedStatementEntry": { + "type": "object", + "required": ["path", "line", "dialect"], + "properties": { + "path": { "type": "string" }, + "line": { "type": "integer", "minimum": 1 }, + "dialect": { "type": "string" } + }, + "additionalProperties": false + }, + "SqlSchemaSummary": { + "type": "object", + "required": ["dialect", "tables"], + "properties": { + "package": { "type": "string" }, + "dialect": { "type": "string" }, + "tables": { "type": "integer", "minimum": 0 } + }, + "additionalProperties": false + }, "BudgetFailure": { "type": "object", "required": ["metric", "ratio", "budget"], diff --git a/crates/report/src/sarif.rs b/crates/report/src/sarif.rs index fb5f1ccf..89008b8d 100644 --- a/crates/report/src/sarif.rs +++ b/crates/report/src/sarif.rs @@ -1,4 +1,4 @@ -use std::collections::{BTreeMap, HashSet}; +use std::collections::{BTreeMap, BTreeSet, HashSet}; use serde::Serialize; @@ -10,14 +10,15 @@ use codeint_model::{Metric, SourceSet}; use crate::schema::{ BUILT_IN_METRICS, BuiltInMetricDescriptor, COGNITIVE_COMPLEXITY_DESCRIPTOR, - DEV_IN_PRODUCTION_DEPENDENCIES_DESCRIPTOR, ORPHAN_FILES_DESCRIPTOR, TEST_GAP_DESCRIPTOR, - UNLISTED_DEPENDENCIES_DESCRIPTOR, UNUSED_DEPENDENCIES_DESCRIPTOR, built_in_metric_descriptor, + DEV_IN_PRODUCTION_DEPENDENCIES_DESCRIPTOR, HAZARDS_DESCRIPTOR, ORPHAN_FILES_DESCRIPTOR, + TEST_GAP_DESCRIPTOR, UNLISTED_DEPENDENCIES_DESCRIPTOR, UNUSED_DEPENDENCIES_DESCRIPTOR, + built_in_metric_descriptor, }; use crate::{ BoundaryFindingRow, COGNITIVE_COMPLEXITY_KEY, CloneFamilyFinding, CloneGroupFinding, CloneLocation, CognitiveComplexityFinding, ErodedFunctionFinding, ExternalMetricFinding, - FlaggedLineRow, ImportCycleFinding, ImportedDependencyRow, OrphanFileRow, Report, - SourceSetSection, TestGapFindingRow, UnusedDependencyRow, + FlaggedLineRow, HazardLineRow, ImportCycleFinding, ImportedDependencyRow, OrphanFileRow, + Report, SourceSetSection, TestGapFindingRow, UnusedDependencyRow, }; #[cfg(test)] @@ -161,6 +162,7 @@ pub(crate) struct ListedFindings<'findings> { pub(crate) boundaries: &'findings [BoundaryFindingRow], pub(crate) orphan_files: &'findings [OrphanFileRow], pub(crate) test_gap: &'findings [TestGapFindingRow], + pub(crate) hazards: &'findings [HazardLineRow], pub(crate) external_metrics: Vec>, } @@ -226,19 +228,18 @@ impl SarifLog { ) }); let dependency_rules = register_dependency_rules(&mut rules, &dependencies); + let hazard_rule_indices = register_hazard_rules(&mut rules, &collected); let external_rule_indices = register_external_rules(&mut rules, &collected); + let optional_rules = OptionalRuleIndices { + boundaries: boundaries_rule_index, + orphan_files: orphan_files_rule_index, + test_gap: test_gap_rule_index, + hazards: &hazard_rule_indices, + external: &external_rule_indices, + }; let mut all_results: Vec = collected .iter() - .flat_map(|(source_set, listed)| { - results( - *source_set, - listed, - boundaries_rule_index, - orphan_files_rule_index, - test_gap_rule_index, - &external_rule_indices, - ) - }) + .flat_map(|(source_set, listed)| results(*source_set, listed, &optional_rules)) .collect(); all_results.extend(dependency_results(&dependencies, &dependency_rules)); SarifLog { @@ -282,6 +283,40 @@ fn rule_from_descriptor(id: &str, info: BuiltInMetricDescriptor) -> Rule { } } +struct OptionalRuleIndices<'a> { + boundaries: Option, + orphan_files: Option, + test_gap: Option, + hazards: &'a BTreeMap, + external: &'a BTreeMap, +} + +fn register_hazard_rules( + rules: &mut Vec, + collected: &[(SourceSet, ListedFindings<'_>)], +) -> BTreeMap { + let unique_rules: BTreeSet<&str> = collected + .iter() + .flat_map(|(_, listed)| listed.hazards.iter().map(|finding| finding.rule.as_str())) + .collect(); + let mut indices = BTreeMap::new(); + for rule_name in unique_rules { + let description = format!("Hazard line matched rule {rule_name}."); + let index = push_rule( + rules, + Rule { + id: rule_name.to_owned(), + name: rule_name.to_owned(), + short_description: Text::from(description.as_str()), + full_description: Text::from(description.as_str()), + help: Text::from(HAZARDS_DESCRIPTOR.help), + }, + ); + indices.insert(rule_name.to_owned(), index); + } + indices +} + fn register_external_rules( rules: &mut Vec, collected: &[(SourceSet, ListedFindings<'_>)], @@ -563,6 +598,10 @@ impl<'findings> ListedFindings<'findings> { .test_gap .as_ref() .map_or(&[], |test_gap| test_gap.findings.listed.as_slice()), + hazards: section + .hazards + .as_ref() + .map_or(&[], |hazards| hazards.findings.listed.as_slice()), external_metrics: section .external_metrics .iter() @@ -580,10 +619,7 @@ impl<'findings> ListedFindings<'findings> { fn results( source_set: SourceSet, listed: &ListedFindings<'_>, - boundaries_rule_index: Option, - orphan_files_rule_index: Option, - test_gap_rule_index: Option, - external_rule_indices: &BTreeMap, + indices: &OptionalRuleIndices<'_>, ) -> Vec { let eroded_functions = listed.eroded_functions.iter().map(|function| { metric_result( @@ -643,7 +679,7 @@ fn results( .unwrap_or_default(); SarifResult { rule_id: "boundaries".to_owned(), - rule_index: boundaries_rule_index.unwrap_or_default(), + rule_index: indices.boundaries.unwrap_or_default(), level: "note", message: Text { text: finding.message.clone(), @@ -661,7 +697,7 @@ fn results( }); let orphan_files = listed.orphan_files.iter().map(|finding| SarifResult { rule_id: "orphan_files".to_owned(), - rule_index: orphan_files_rule_index.unwrap_or_default(), + rule_index: indices.orphan_files.unwrap_or_default(), level: "note", message: Text { text: finding.message.clone(), @@ -684,7 +720,7 @@ fn results( let test_gap = listed.test_gap.iter().map(|finding| { function_metric_result( TEST_GAP_METRIC_KEY, - test_gap_rule_index.unwrap_or_default(), + indices.test_gap.unwrap_or_default(), source_set, &finding.id, test_gap_finding_message(finding), @@ -692,8 +728,25 @@ fn results( finding.line, ) }); + let hazards = listed.hazards.iter().map(|finding| { + let rule_index = indices + .hazards + .get(&finding.rule) + .copied() + .unwrap_or_default(); + function_metric_result( + &finding.rule, + rule_index, + source_set, + &finding.id, + format!("Hazard line: rule {}.", finding.rule), + &finding.path, + finding.line, + ) + }); let external_findings = listed.external_metrics.iter().flat_map(|external| { - let rule_index = external_rule_indices + let rule_index = indices + .external .get(external.key) .copied() .unwrap_or_default(); @@ -728,6 +781,7 @@ fn results( .chain(boundaries) .chain(orphan_files) .chain(test_gap) + .chain(hazards) .chain(external_findings) .collect() } diff --git a/crates/report/src/sarif/tests.rs b/crates/report/src/sarif/tests.rs index 2a84d9eb..b269bc46 100644 --- a/crates/report/src/sarif/tests.rs +++ b/crates/report/src/sarif/tests.rs @@ -3,7 +3,7 @@ use codeint_model::SourceSet; use super::{ListedFindings, SarifLog, relative_uri}; use crate::{ CloneFamilyFinding, CloneGroupFinding, CloneLocation, CognitiveComplexityFinding, Decimal, - ErodedFunctionFinding, FlaggedLineRow, ImportCycleFinding, + ErodedFunctionFinding, FlaggedLineRow, HazardLineRow, ImportCycleFinding, }; fn empty_listed_findings<'a>() -> ListedFindings<'a> { @@ -18,6 +18,7 @@ fn empty_listed_findings<'a>() -> ListedFindings<'a> { boundaries: &[], orphan_files: &[], test_gap: &[], + hazards: &[], external_metrics: Vec::new(), } } @@ -457,3 +458,59 @@ fn sarif_does_not_leak_member_clone_groups_of_families_beyond_display_cap() { diff.render(ReportFormat::Toon).expect("direct diff toon") ); } + +#[test] +fn sarif_emits_hazard_rules_by_rule_name_and_never_includes_source_text() { + let hazards = [ + HazardLineRow { + id: "aaaa000000000001".to_owned(), + path: "db/query.sql".to_owned(), + line: 7, + rule: "select-star".to_owned(), + owners: Vec::new(), + }, + HazardLineRow { + id: "bbbb000000000002".to_owned(), + path: "db/query.sql".to_owned(), + line: 12, + rule: "plain-text-secret".to_owned(), + owners: Vec::new(), + }, + ]; + let listed = ListedFindings { + hazards: &hazards, + ..empty_listed_findings() + }; + + let log = serde_json::to_value(SarifLog::listing( + std::iter::once((SourceSet::Production, listed)), + super::ListedDependencies::EMPTY, + )) + .expect("SARIF serializes"); + + let rules = log["runs"][0]["tool"]["driver"]["rules"] + .as_array() + .expect("rules"); + let results = log["runs"][0]["results"].as_array().expect("results"); + assert_eq!(results.len(), 2); + for (result, (expected_rule, expected_line, expected_id)) in results.iter().zip([ + ("select-star", 7u64, "aaaa000000000001"), + ("plain-text-secret", 12u64, "bbbb000000000002"), + ]) { + assert_eq!(result["ruleId"], expected_rule); + let idx = result["ruleIndex"].as_u64().expect("ruleIndex") as usize; + assert_eq!(rules[idx]["id"], expected_rule); + assert_eq!( + rules[idx]["shortDescription"]["text"], + format!("Hazard line matched rule {expected_rule}.") + ); + assert_eq!( + result["locations"][0]["physicalLocation"]["region"]["startLine"], + expected_line + ); + assert_eq!( + result["partialFingerprints"]["codeintFindingId"], + expected_id + ); + } +} diff --git a/crates/report/src/schema.rs b/crates/report/src/schema.rs index 2f4674d8..3c0bdfb0 100644 --- a/crates/report/src/schema.rs +++ b/crates/report/src/schema.rs @@ -1,9 +1,11 @@ +use std::collections::BTreeMap; + use codeint_config::{ CliCommandSchema, CliSchema, NewFindingsRule, OutputFormatSchema, RegressionLimits, SchemaFormat, configuration_schema, }; use codeint_metrics::{ - DEV_IN_PRODUCTION_DEPENDENCIES_METRIC_KEY, TEST_GAP_METRIC_KEY, + DEV_IN_PRODUCTION_DEPENDENCIES_METRIC_KEY, HAZARDS_METRIC_KEY, TEST_GAP_METRIC_KEY, UNLISTED_DEPENDENCIES_METRIC_KEY, UNUSED_DEPENDENCIES_METRIC_KEY, }; use codeint_model::{Metric, SourceSet}; @@ -109,6 +111,13 @@ pub(crate) const TEST_GAP_DESCRIPTOR: BuiltInMetricDescriptor = BuiltInMetricDes help: "Add tests that execute the uncovered lines of this function, starting with the heaviest untested functions first.", }; +pub(crate) const HAZARDS_DESCRIPTOR: BuiltInMetricDescriptor = BuiltInMetricDescriptor { + name: "Hazards", + short_description: "A Hazard line: a parsed pattern likely to cause wrong results, slow execution, or a security exposure", + full_description: "Hazards is the share of source lines that are Hazard lines in languages that have Hazard line rules. Each Hazard line Finding names its path, line, and rule, and never the source text.", + help: "Rewrite the statement to remove the hazard named by the rule, or turn off the rule in hazards.disabled_rules in codeint.json.", +}; + #[derive(Debug, Clone, PartialEq, Serialize)] pub struct SchemaReport { name: String, @@ -118,12 +127,20 @@ pub struct SchemaReport { metrics: Vec, configuration_keys: Vec, source_sets: Vec<&'static str>, - languages: Vec, + languages: Vec, output_formats: Vec, mcp_tools: Vec, exit_codes: Vec, } +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +struct LanguageSchemaEntry { + name: String, + extensions: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + hazard_rules: Vec, +} + #[derive(Debug, Clone, PartialEq, Serialize)] pub struct MetricSchema { key: &'static str, @@ -177,6 +194,7 @@ impl SchemaReport { for (key, descriptor) in [ (COGNITIVE_COMPLEXITY_KEY, COGNITIVE_COMPLEXITY_DESCRIPTOR), ("orphan_files", ORPHAN_FILES_DESCRIPTOR), + (HAZARDS_METRIC_KEY, HAZARDS_DESCRIPTOR), ] { let limit = default_limits.limit_for_key(SourceSet::Production, key); metrics.push(metric_schema(key, descriptor, limit)); @@ -203,6 +221,14 @@ impl SchemaReport { TEST_GAP_DESCRIPTOR, )); let source_sets = SOURCE_SETS.into_iter().map(SourceSet::key).collect(); + let languages = languages + .into_iter() + .map(|language| LanguageSchemaEntry { + name: language.name, + extensions: language.extensions, + hazard_rules: Vec::new(), + }) + .collect(); SchemaReport { name: cli.name, version: cli.version, @@ -218,6 +244,18 @@ impl SchemaReport { } } + pub fn with_language_hazard_rules( + mut self, + mut rules_by_language: BTreeMap>, + ) -> SchemaReport { + for language in &mut self.languages { + if let Some(rules) = rules_by_language.remove(&language.name) { + language.hazard_rules = rules; + } + } + self + } + pub fn render(&self, format: SchemaFormat) -> Result { match format { SchemaFormat::Json => crate::render_json(self), diff --git a/crates/report/src/trend.rs b/crates/report/src/trend.rs index 9331838b..71336155 100644 --- a/crates/report/src/trend.rs +++ b/crates/report/src/trend.rs @@ -44,8 +44,10 @@ struct TrendRow { cognitive_complexity: Decimal, duplication: Decimal, verbosity: Decimal, - #[serde(default, skip_serializing_if = "Option::is_none")] + #[serde(skip_serializing_if = "Option::is_none")] import_cycles: Option, + #[serde(skip_serializing_if = "Option::is_none")] + hazards: Option, #[serde(flatten)] external_metrics: BTreeMap, } @@ -138,6 +140,10 @@ impl TrendRow { .import_cycles .as_ref() .map(|cycles| Decimal::rounded(cycles.ratio)), + hazards: measured + .hazards + .as_ref() + .map(|hazards| Decimal::rounded(hazards.ratio)), external_metrics: measured .external_metrics .iter() diff --git a/crates/report/src/trend/markdown.rs b/crates/report/src/trend/markdown.rs index c677501c..c21d9ddd 100644 --- a/crates/report/src/trend/markdown.rs +++ b/crates/report/src/trend/markdown.rs @@ -27,16 +27,20 @@ pub(super) fn render(report: &TrendReport) -> String { .into_iter() .collect(); let show_import_cycles = rows.iter().any(|row| row.import_cycles.is_some()); + let show_hazards = rows.iter().any(|row| row.hazards.is_some()); let mut columns: Vec<&str> = BASE_COLUMNS.to_vec(); if show_import_cycles { columns.push("Import cycles"); } + if show_hazards { + columns.push("Hazards"); + } columns.extend(external_keys.iter().map(String::as_str)); blocks.push(format!("## {name}")); blocks.push(table( &columns, rows.iter() - .map(|row| row_cells(row, show_import_cycles, &external_keys)) + .map(|row| row_cells(row, show_import_cycles, show_hazards, &external_keys)) .collect(), )); } @@ -48,7 +52,12 @@ fn measured_sentence(commits: usize) -> String { format!("codeint measured {commits} {noun} of the main line of HEAD, oldest first.") } -fn row_cells(row: &TrendRow, show_import_cycles: bool, external_keys: &[String]) -> Vec { +fn row_cells( + row: &TrendRow, + show_import_cycles: bool, + show_hazards: bool, + external_keys: &[String], +) -> Vec { let mut cells = vec![ code(&row.commit), row.committed_on.clone(), @@ -65,6 +74,13 @@ fn row_cells(row: &TrendRow, show_import_cycles: bool, external_keys: &[String]) .map_or_else(|| "-".to_owned(), |decimal| decimal.0.to_string()); cells.push(value); } + if show_hazards { + let value = row + .hazards + .as_ref() + .map_or_else(|| "-".to_owned(), |decimal| decimal.0.to_string()); + cells.push(value); + } for key in external_keys { let value = row .external_metrics diff --git a/crates/report/tests/report_schema.rs b/crates/report/tests/report_schema.rs index 023794c9..60e0138e 100644 --- a/crates/report/tests/report_schema.rs +++ b/crates/report/tests/report_schema.rs @@ -3,10 +3,13 @@ use std::path::PathBuf; use codeint_config::{Budgets, DependenciesConfig, DuplicationConfig, FindingsShown, ReportFormat}; use codeint_model::language::Function; use codeint_model::{ - CodeModel, FileModel, FunctionCoverage, LanguageFacts, ReferenceRanges, RepoPath, SourceFile, - SourceSet, Workspace, + CodeModel, FileModel, FunctionCoverage, HazardLine, LanguageFacts, ReferenceRanges, RepoPath, + SourceFile, SourceSet, Workspace, +}; +use codeint_report::{ + MeasuredLanguage, OwnershipOptions, RejectedStatementEntry, Report, ReportExtras, + ReportOptions, SqlSchemaSummary, report_schema, }; -use codeint_report::{MeasuredLanguage, OwnershipOptions, Report, ReportOptions, report_schema}; use serde_json::Value; fn published_report_schema_path() -> PathBuf { @@ -102,11 +105,19 @@ fn check_array_schema(value: &Value, schema: &Value, root: &Value, path: &str) { } } -fn sample_model(has_coverage: bool) -> CodeModel { +fn sample_model(has_coverage: bool, has_hazard_rules: bool) -> CodeModel { let coverage = has_coverage.then_some(FunctionCoverage { listed_lines: 4, executed_lines: 1, }); + let hazard_lines = if has_hazard_rules { + vec![HazardLine { + line: 2, + rule: "select-star".to_owned(), + }] + } else { + Vec::new() + }; CodeModel { workspace: Workspace::new([RepoPath::new("packages/api").expect("pkg")]), files: vec![SourceFile { @@ -125,7 +136,7 @@ fn sample_model(has_coverage: bool) -> CodeModel { }], tokens: Vec::new(), flagged_lines: Vec::new(), - hazard_lines: Vec::new(), + hazard_lines, runtime_imports: Vec::new(), program_start: false, }, @@ -133,7 +144,7 @@ fn sample_model(has_coverage: bool) -> CodeModel { languages: vec![LanguageFacts { language: "typescript-javascript".to_owned(), has_coverage, - has_hazard_rules: true, + has_hazard_rules, has_imports: true, }], ..CodeModel::default() @@ -156,10 +167,10 @@ fn published_report_schema_matches_generated_and_validates_reports_with_and_with let dependencies = DependenciesConfig::default(); let budgets = Budgets::default(); - let with_gap = Report::summarize_with_options( + let with_gap = Report::summarize_with_extras( vec![MeasuredLanguage { plugin: "typescript-javascript".to_owned(), - model: sample_model(true), + model: sample_model(true, true), reference_ranges: ReferenceRanges::default(), has_imports: true, }], @@ -179,8 +190,19 @@ fn published_report_schema_matches_generated_and_validates_reports_with_and_with coverage_reports_named: true, unmatched_coverage_paths: &["missing/file.ts".to_owned()], }, + ReportExtras::default() + .with_rejected_statements(vec![RejectedStatementEntry { + path: "packages/api/db/bad.sql".to_owned(), + line: 9, + dialect: "postgresql".to_owned(), + }]) + .with_sql_schemas(vec![SqlSchemaSummary { + package: Some("packages/api".to_owned()), + dialect: "postgresql".to_owned(), + tables: 3, + }]), ) - .expect("report with test gap"); + .expect("report with test gap and hazards"); let with_gap_json: Value = serde_json::from_str(&with_gap.render(ReportFormat::Json).expect("json")) .expect("valid JSON"); @@ -189,6 +211,10 @@ fn published_report_schema_matches_generated_and_validates_reports_with_and_with with_gap_json["source_sets"]["production"]["test_gap"]["ratio"], 0.75 ); + assert_eq!( + with_gap_json["source_sets"]["production"]["hazards"]["hazard_lines"], + 1 + ); let api_package = with_gap_json["source_sets"]["production"]["packages"] .as_array() .expect("packages") @@ -196,11 +222,12 @@ fn published_report_schema_matches_generated_and_validates_reports_with_and_with .find(|pkg| pkg["path"] == "packages/api") .expect("packages/api entry"); assert_eq!(api_package["test_gap"]["ratio"], 0.75); + assert_eq!(api_package["hazards"]["hazard_lines"], 1); let without_gap = Report::summarize( vec![MeasuredLanguage { plugin: "typescript-javascript".to_owned(), - model: sample_model(false), + model: sample_model(false, false), reference_ranges: ReferenceRanges::default(), has_imports: true, }], @@ -217,5 +244,10 @@ fn published_report_schema_matches_generated_and_validates_reports_with_and_with .get("test_gap") .is_none() ); + assert!( + without_gap_json["source_sets"]["production"] + .get("hazards") + .is_none() + ); assert!(without_gap_json["test_gap_note"].is_string()); } diff --git a/schema/codeint-report.schema.json b/schema/codeint-report.schema.json index 73573b9f..56bb9883 100644 --- a/schema/codeint-report.schema.json +++ b/schema/codeint-report.schema.json @@ -58,6 +58,20 @@ } } }, + "rejected_statements": { + "type": "array", + "description": "Statements that a Language plugin's parser could not parse; they still count in token Metrics and receive no statement rules.", + "items": { + "$ref": "#/$defs/RejectedStatementEntry" + } + }, + "sql_schemas": { + "type": "array", + "description": "Table counts of each SQL schema built per Workspace package (or repository root) and Dialect.", + "items": { + "$ref": "#/$defs/SqlSchemaSummary" + } + }, "declaration_only": { "type": "array", "items": { @@ -169,6 +183,9 @@ "test_gap": { "$ref": "#/$defs/TestGapSection" }, + "hazards": { + "$ref": "#/$defs/HazardsSection" + }, "packages": { "type": "array", "items": { @@ -215,6 +232,9 @@ "type": "object" }, "test_gap": false, + "hazards": { + "$ref": "#/$defs/HazardsSection" + }, "packages": { "type": "array", "items": { @@ -350,6 +370,9 @@ }, "test_gap": { "$ref": "#/$defs/PackageTestGap" + }, + "hazards": { + "$ref": "#/$defs/PackageHazards" } }, "additionalProperties": false @@ -378,6 +401,138 @@ }, "additionalProperties": false }, + "HazardsSection": { + "type": "object", + "description": "Hazards for this Source set; omitted when no measured language has Hazard line rules.", + "required": [ + "ratio", + "hazard_lines", + "source_lines", + "findings" + ], + "properties": { + "ratio": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "hazard_lines": { + "type": "integer", + "minimum": 0 + }, + "source_lines": { + "type": "integer", + "minimum": 0 + }, + "findings": { + "type": "array", + "items": { + "$ref": "#/$defs/HazardLineFinding" + } + }, + "findings_left_out": { + "type": "integer", + "minimum": 1 + } + }, + "additionalProperties": false + }, + "HazardLineFinding": { + "type": "object", + "required": [ + "id", + "path", + "line", + "rule" + ], + "properties": { + "id": { + "type": "string" + }, + "path": { + "type": "string" + }, + "line": { + "type": "integer", + "minimum": 1 + }, + "rule": { + "type": "string" + }, + "owners": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "additionalProperties": false + }, + "PackageHazards": { + "type": "object", + "required": [ + "ratio", + "hazard_lines", + "source_lines" + ], + "properties": { + "ratio": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "hazard_lines": { + "type": "integer", + "minimum": 0 + }, + "source_lines": { + "type": "integer", + "minimum": 0 + } + }, + "additionalProperties": false + }, + "RejectedStatementEntry": { + "type": "object", + "required": [ + "path", + "line", + "dialect" + ], + "properties": { + "path": { + "type": "string" + }, + "line": { + "type": "integer", + "minimum": 1 + }, + "dialect": { + "type": "string" + } + }, + "additionalProperties": false + }, + "SqlSchemaSummary": { + "type": "object", + "required": [ + "dialect", + "tables" + ], + "properties": { + "package": { + "type": "string" + }, + "dialect": { + "type": "string" + }, + "tables": { + "type": "integer", + "minimum": 0 + } + }, + "additionalProperties": false + }, "BudgetFailure": { "type": "object", "required": [ From a4df81b4d78663044280dc5d209ed4c70b61e90e Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Tue, 24 Nov 2026 21:23:49 +0800 Subject: [PATCH 04/12] feat(plugins): add SQL schema builder and schema-backed hazard rules --- plugins/languages/sql/src/lib.rs | 1 + plugins/languages/sql/src/schema.rs | 10 + plugins/languages/sql/src/schema/builder.rs | 568 ++++++++++++++++++ plugins/languages/sql/src/schema/expr.rs | 456 +++++++++++++++ plugins/languages/sql/src/schema/rules.rs | 602 ++++++++++++++++++++ plugins/languages/sql/src/schema/scope.rs | 304 ++++++++++ plugins/languages/sql/src/schema/tests.rs | 305 ++++++++++ plugins/languages/sql/src/schema/types.rs | 114 ++++ plugins/languages/sql/tests/schema_rules.rs | 297 ++++++++++ 9 files changed, 2657 insertions(+) create mode 100644 plugins/languages/sql/src/schema.rs create mode 100644 plugins/languages/sql/src/schema/builder.rs create mode 100644 plugins/languages/sql/src/schema/expr.rs create mode 100644 plugins/languages/sql/src/schema/rules.rs create mode 100644 plugins/languages/sql/src/schema/scope.rs create mode 100644 plugins/languages/sql/src/schema/tests.rs create mode 100644 plugins/languages/sql/src/schema/types.rs create mode 100644 plugins/languages/sql/tests/schema_rules.rs diff --git a/plugins/languages/sql/src/lib.rs b/plugins/languages/sql/src/lib.rs index 9a000aa6..e748f752 100644 --- a/plugins/languages/sql/src/lib.rs +++ b/plugins/languages/sql/src/lib.rs @@ -2,6 +2,7 @@ mod flagged; mod parser; +pub mod schema; mod source_set; mod statements; mod tokenize; diff --git a/plugins/languages/sql/src/schema.rs b/plugins/languages/sql/src/schema.rs new file mode 100644 index 00000000..95b6e7b4 --- /dev/null +++ b/plugins/languages/sql/src/schema.rs @@ -0,0 +1,10 @@ +mod builder; +mod expr; +mod rules; +mod scope; +#[cfg(test)] +mod tests; +mod types; + +pub use rules::{collect_schema_hazards, schema_hazard_rules}; +pub use types::{ColumnTypeClass, IndexSchema, SqlSchema, TableSchema}; diff --git a/plugins/languages/sql/src/schema/builder.rs b/plugins/languages/sql/src/schema/builder.rs new file mode 100644 index 00000000..ee084c82 --- /dev/null +++ b/plugins/languages/sql/src/schema/builder.rs @@ -0,0 +1,568 @@ +use std::collections::BTreeMap; + +use sqlparser::ast::{ + AlterColumnOperation, AlterTable, AlterTableOperation, ColumnDef, ColumnOption, CreateIndex, + CreateTable, DataType, Expr, Ident, IndexColumn, ObjectName, ObjectType, RenameTableNameKind, + Statement, TableConstraint, +}; + +use crate::ParsedSqlStatement; +use crate::schema::types::{ + ColumnTypeClass, IndexSchema, SqlSchema, TableKey, TableSchema, normalize_ident, + object_name_last_ident, split_object_name, +}; + +impl SqlSchema { + pub fn build<'a>( + files_in_path_order: impl IntoIterator, + ) -> SqlSchema { + let mut schema = SqlSchema::default(); + for statements in files_in_path_order { + for parsed in statements { + apply_statement(&mut schema, &parsed.statement); + } + } + schema + } +} + +fn apply_statement(schema: &mut SqlSchema, stmt: &Statement) { + match stmt { + Statement::CreateTable(create_table) => apply_create_table(schema, create_table), + Statement::CreateIndex(create_index) => apply_create_index(schema, create_index), + Statement::AlterTable(alter_table) => apply_alter_table(schema, alter_table), + Statement::Drop { + object_type, + names, + table, + .. + } => apply_drop(schema, *object_type, names, table.as_ref()), + _ => {} + } +} + +fn apply_create_table(schema: &mut SqlSchema, create: &CreateTable) { + if create.columns.is_empty() && create.query.is_some() { + return; + } + let Some((table_schema, table_name)) = split_object_name(&create.name) else { + return; + }; + let mut table = TableSchema { + schema: table_schema.clone(), + name: table_name.clone(), + columns: BTreeMap::new(), + primary_key: Vec::new(), + indexes: Vec::new(), + }; + for column in &create.columns { + apply_column_def(&mut table, column); + } + for constraint in &create.constraints { + apply_table_constraint(&mut table, constraint); + } + if table.primary_key.is_empty() + && let Some(expr) = &create.primary_key + { + table.primary_key = extract_pk_expr_columns(expr); + } + schema.tables.insert((table_schema, table_name), table); +} + +fn apply_column_def(table: &mut TableSchema, column: &ColumnDef) { + let col_name = normalize_ident(&column.name); + table + .columns + .insert(col_name.clone(), classify_data_type(&column.data_type)); + for opt_def in &column.options { + apply_column_option( + table, + &col_name, + opt_def.name.as_ref().map(normalize_ident), + &opt_def.option, + ); + } +} + +fn apply_column_option( + table: &mut TableSchema, + col_name: &str, + constraint_name: Option, + option: &ColumnOption, +) { + match option { + ColumnOption::PrimaryKey(_) => { + table.primary_key = vec![col_name.to_owned()]; + } + ColumnOption::Unique(unique) => { + let name = unique + .name + .as_ref() + .or(unique.index_name.as_ref()) + .map(normalize_ident) + .or(constraint_name); + upsert_index( + &mut table.indexes, + IndexSchema { + name, + columns: vec![col_name.to_owned()], + }, + ); + } + _ => {} + } +} + +fn apply_table_constraint(table: &mut TableSchema, constraint: &TableConstraint) { + match constraint { + TableConstraint::PrimaryKey(pk) => set_primary_key_from_columns(table, &pk.columns), + TableConstraint::Unique(unique) => { + let name = unique.name.as_ref().or(unique.index_name.as_ref()); + add_index_from_columns(table, name, &unique.columns); + } + TableConstraint::Index(index) => { + add_index_from_columns(table, index.name.as_ref(), &index.columns); + } + TableConstraint::FulltextOrSpatial(index) => { + add_index_from_columns(table, index.opt_index_name.as_ref(), &index.columns); + } + TableConstraint::PrimaryKeyUsingIndex(using_idx) => { + promote_index_to_pk(table, &normalize_ident(&using_idx.index_name)); + } + _ => {} + } +} + +fn set_primary_key_from_columns(table: &mut TableSchema, columns: &[IndexColumn]) { + let cols = extract_index_columns(columns); + if !cols.is_empty() { + table.primary_key = cols; + } +} + +fn add_index_from_columns(table: &mut TableSchema, name: Option<&Ident>, columns: &[IndexColumn]) { + let cols = extract_index_columns(columns); + if !cols.is_empty() { + upsert_index( + &mut table.indexes, + IndexSchema { + name: name.map(normalize_ident), + columns: cols, + }, + ); + } +} + +fn promote_index_to_pk(table: &mut TableSchema, idx_name: &str) { + if let Some(found) = table + .indexes + .iter() + .find(|idx| idx.name.as_deref() == Some(idx_name)) + { + table.primary_key = found.columns.clone(); + } +} + +fn apply_create_index(schema: &mut SqlSchema, create: &CreateIndex) { + let Some((table_schema, table_name)) = split_object_name(&create.table_name) else { + return; + }; + let Some(key) = schema.resolve_table_key(table_schema.as_deref(), &table_name) else { + return; + }; + let columns = extract_index_columns(&create.columns); + if columns.is_empty() { + return; + } + let name = create.name.as_ref().and_then(object_name_last_ident); + if let Some(table) = schema.tables.get_mut(&key) { + upsert_index(&mut table.indexes, IndexSchema { name, columns }); + } +} + +fn apply_alter_table(schema: &mut SqlSchema, alter: &AlterTable) { + let Some((table_schema, table_name)) = split_object_name(&alter.name) else { + return; + }; + let Some(mut key) = schema.resolve_table_key(table_schema.as_deref(), &table_name) else { + return; + }; + for operation in &alter.operations { + key = apply_alter_operation(schema, key, operation); + } +} + +fn apply_alter_operation( + schema: &mut SqlSchema, + key: TableKey, + operation: &AlterTableOperation, +) -> TableKey { + if let AlterTableOperation::RenameTable { table_name } = operation { + return rename_table_entry(schema, key, table_name); + } + let Some(table) = schema.tables.get_mut(&key) else { + return key; + }; + apply_table_mutation(table, operation); + key +} + +fn rename_table_entry( + schema: &mut SqlSchema, + old_key: TableKey, + target: &RenameTableNameKind, +) -> TableKey { + let target_name = match target { + RenameTableNameKind::As(name) | RenameTableNameKind::To(name) => name, + }; + let Some((new_schema, new_name)) = split_object_name(target_name) else { + return old_key; + }; + let Some(mut table) = schema.tables.remove(&old_key) else { + return old_key; + }; + let effective_schema = new_schema.or(table.schema.clone()); + table.schema = effective_schema.clone(); + table.name = new_name.clone(); + let new_key = (effective_schema, new_name); + schema.tables.insert(new_key.clone(), table); + new_key +} + +fn apply_table_mutation(table: &mut TableSchema, operation: &AlterTableOperation) { + match operation { + AlterTableOperation::AddColumn { column_def, .. } => apply_column_def(table, column_def), + AlterTableOperation::DropColumn { column_names, .. } => { + for ident in column_names { + drop_column_from_table(table, &normalize_ident(ident)); + } + } + AlterTableOperation::RenameColumn { + old_column_name, + new_column_name, + } => rename_column_in_table( + table, + &normalize_ident(old_column_name), + &normalize_ident(new_column_name), + ), + AlterTableOperation::ChangeColumn { .. } + | AlterTableOperation::ModifyColumn { .. } + | AlterTableOperation::AlterColumn { .. } => apply_column_type_alter(table, operation), + _ => apply_constraint_alter(table, operation), + } +} + +fn apply_column_type_alter(table: &mut TableSchema, operation: &AlterTableOperation) { + match operation { + AlterTableOperation::ChangeColumn { + old_name, + new_name, + data_type, + options, + .. + } => { + let new = normalize_ident(new_name); + rename_column_in_table(table, &normalize_ident(old_name), &new); + update_column_type_and_options(table, &new, data_type, options); + } + AlterTableOperation::ModifyColumn { + col_name, + data_type, + options, + .. + } => { + update_column_type_and_options(table, &normalize_ident(col_name), data_type, options); + } + AlterTableOperation::AlterColumn { + column_name, + op: AlterColumnOperation::SetDataType { data_type, .. }, + } => { + let col = normalize_ident(column_name); + if table.columns.contains_key(&col) { + table.columns.insert(col, classify_data_type(data_type)); + } + } + _ => {} + } +} + +fn update_column_type_and_options( + table: &mut TableSchema, + col: &str, + data_type: &DataType, + options: &[ColumnOption], +) { + table + .columns + .insert(col.to_owned(), classify_data_type(data_type)); + for option in options { + apply_column_option(table, col, None, option); + } +} + +fn apply_constraint_alter(table: &mut TableSchema, operation: &AlterTableOperation) { + match operation { + AlterTableOperation::AddConstraint { constraint, .. } => { + apply_table_constraint(table, constraint); + } + AlterTableOperation::DropConstraint { name, .. } + | AlterTableOperation::DropIndex { name } => { + remove_named_index(table, &normalize_ident(name)); + } + AlterTableOperation::DropPrimaryKey { .. } => table.primary_key.clear(), + _ => {} + } +} + +fn remove_named_index(table: &mut TableSchema, target: &str) { + table + .indexes + .retain(|idx| idx.name.as_deref() != Some(target)); +} + +fn drop_column_from_table(table: &mut TableSchema, col: &str) { + table.columns.remove(col); + table.primary_key.retain(|c| c != col); + for idx in &mut table.indexes { + idx.columns.retain(|c| c != col); + } + table.indexes.retain(|idx| !idx.columns.is_empty()); +} + +fn rename_column_in_table(table: &mut TableSchema, old: &str, new: &str) { + if let Some(ty) = table.columns.remove(old) { + table.columns.insert(new.to_owned(), ty); + } + for col in &mut table.primary_key { + if col == old { + *col = new.to_owned(); + } + } + for idx in &mut table.indexes { + for col in &mut idx.columns { + if col == old { + *col = new.to_owned(); + } + } + } +} + +fn apply_drop( + schema: &mut SqlSchema, + object_type: ObjectType, + names: &[ObjectName], + table_target: Option<&ObjectName>, +) { + match object_type { + ObjectType::Table => drop_tables(schema, names), + ObjectType::Index => match table_target { + Some(target) => drop_indexes_on_table(schema, names, target), + None => drop_indexes_across_tables(schema, names), + }, + _ => {} + } +} + +fn drop_tables(schema: &mut SqlSchema, names: &[ObjectName]) { + for obj_name in names { + if let Some((table_schema, table_name)) = split_object_name(obj_name) + && let Some(key) = schema.resolve_table_key(table_schema.as_deref(), &table_name) + { + schema.tables.remove(&key); + } + } +} + +fn drop_indexes_on_table(schema: &mut SqlSchema, names: &[ObjectName], target_obj: &ObjectName) { + let Some((table_schema, table_name)) = split_object_name(target_obj) else { + return; + }; + let Some(key) = schema.resolve_table_key(table_schema.as_deref(), &table_name) else { + return; + }; + let Some(table) = schema.tables.get_mut(&key) else { + return; + }; + for idx_name in names.iter().filter_map(object_name_last_ident) { + remove_named_index(table, &idx_name); + } +} + +fn drop_indexes_across_tables(schema: &mut SqlSchema, names: &[ObjectName]) { + for (idx_schema, idx_name) in names.iter().filter_map(split_object_name) { + for table in schema.tables.values_mut() { + if idx_schema.is_none() || table.schema == idx_schema { + remove_named_index(table, &idx_name); + } + } + } +} + +fn upsert_index(indexes: &mut Vec, entry: IndexSchema) { + if let Some(ref name) = entry.name + && let Some(existing) = indexes + .iter_mut() + .find(|idx| idx.name.as_deref() == Some(name.as_str())) + { + *existing = entry; + return; + } + indexes.push(entry); +} + +fn extract_index_columns(columns: &[IndexColumn]) -> Vec { + let mut out = Vec::with_capacity(columns.len()); + for col in columns { + let Some(name) = extract_expr_column_ident(&col.column.expr) else { + break; + }; + out.push(name); + } + out +} + +fn extract_pk_expr_columns(expr: &Expr) -> Vec { + match expr { + Expr::Tuple(items) => items.iter().filter_map(extract_expr_column_ident).collect(), + _ => extract_expr_column_ident(expr).into_iter().collect(), + } +} + +fn extract_expr_column_ident(expr: &Expr) -> Option { + match expr { + Expr::Nested(inner) | Expr::Collate { expr: inner, .. } => extract_expr_column_ident(inner), + Expr::Identifier(ident) => Some(normalize_ident(ident)), + Expr::CompoundIdentifier(idents) => idents.last().map(normalize_ident), + _ => None, + } +} + +pub(crate) fn classify_data_type(data_type: &DataType) -> ColumnTypeClass { + match data_type { + DataType::Nullable(inner) + | DataType::LowCardinality(inner) + | DataType::Collate(inner, _) + | DataType::Zerofill(inner) => classify_data_type(inner), + DataType::Character(_) + | DataType::Char(_) + | DataType::CharacterVarying(_) + | DataType::CharVarying(_) + | DataType::Varchar(_) + | DataType::Nvarchar(_) + | DataType::CharacterLargeObject(_) + | DataType::CharLargeObject(_) + | DataType::Clob(_) + | DataType::Text + | DataType::TinyText + | DataType::MediumText + | DataType::LongText + | DataType::String(_) + | DataType::FixedString(_) => ColumnTypeClass::Text, + DataType::Bool | DataType::Boolean => ColumnTypeClass::Boolean, + DataType::Date + | DataType::Date32 + | DataType::Time(_, _) + | DataType::Datetime(_) + | DataType::Datetime64(_, _) + | DataType::Timestamp(_, _) + | DataType::TimestampNtz(_) + | DataType::Interval { .. } => ColumnTypeClass::Temporal, + DataType::Binary(_) + | DataType::Varbinary(_) + | DataType::Blob(_) + | DataType::TinyBlob + | DataType::MediumBlob + | DataType::LongBlob + | DataType::Bytes(_) + | DataType::Bytea => ColumnTypeClass::Binary, + DataType::Custom(name, _) => classify_custom_type(name), + other if is_numeric_data_type(other) => ColumnTypeClass::Numeric, + _ => ColumnTypeClass::Other, + } +} + +fn is_numeric_data_type(data_type: &DataType) -> bool { + matches!( + data_type, + DataType::Numeric(_) + | DataType::Decimal(_) + | DataType::DecimalUnsigned(_) + | DataType::BigNumeric(_) + | DataType::BigDecimal(_) + | DataType::Dec(_) + | DataType::DecUnsigned(_) + | DataType::Float(_) + | DataType::FloatUnsigned(_) + | DataType::Float4 + | DataType::Float32 + | DataType::Float64 + | DataType::Float8 + | DataType::Real + | DataType::RealUnsigned + | DataType::Double(_) + | DataType::DoubleUnsigned(_) + | DataType::DoublePrecision + | DataType::DoublePrecisionUnsigned + | DataType::TinyInt(_) + | DataType::TinyIntUnsigned(_) + | DataType::UTinyInt + | DataType::Int2(_) + | DataType::Int2Unsigned(_) + | DataType::SmallInt(_) + | DataType::SmallIntUnsigned(_) + | DataType::USmallInt + | DataType::MediumInt(_) + | DataType::MediumIntUnsigned(_) + | DataType::Int(_) + | DataType::IntUnsigned(_) + | DataType::Int4(_) + | DataType::Int4Unsigned(_) + | DataType::Integer(_) + | DataType::IntegerUnsigned(_) + | DataType::Int8(_) + | DataType::Int8Unsigned(_) + | DataType::Int16 + | DataType::Int32 + | DataType::Int64 + | DataType::Int128 + | DataType::Int256 + | DataType::HugeInt + | DataType::UHugeInt + | DataType::UInt8 + | DataType::UInt16 + | DataType::UInt32 + | DataType::UInt64 + | DataType::UInt128 + | DataType::UInt256 + | DataType::BigInt(_) + | DataType::BigIntUnsigned(_) + | DataType::UBigInt + | DataType::Signed + | DataType::SignedInteger + | DataType::Unsigned + | DataType::UnsignedInteger + ) +} + +fn classify_custom_type(name: &ObjectName) -> ColumnTypeClass { + let Some(last) = object_name_last_ident(name) else { + return ColumnTypeClass::Other; + }; + match last.as_str() { + "citext" | "bpchar" | "varchar2" | "nvarchar2" | "nchar" | "ntext" | "tinytext" + | "mediumtext" | "longtext" | "text" | "string" | "varchar" | "char" | "character" + | "clob" => ColumnTypeClass::Text, + "serial" | "bigserial" | "smallserial" | "serial2" | "serial4" | "serial8" | "money" + | "smallmoney" | "number" | "int" | "integer" | "bigint" | "smallint" | "tinyint" + | "mediumint" | "decimal" | "numeric" | "float" | "double" | "real" => { + ColumnTypeClass::Numeric + } + "bool" | "boolean" => ColumnTypeClass::Boolean, + "date" | "time" | "timetz" | "timestamp" | "timestamptz" | "datetime" | "smalldatetime" + | "interval" | "year" => ColumnTypeClass::Temporal, + "blob" | "bytea" | "binary" | "varbinary" | "tinyblob" | "mediumblob" | "longblob" => { + ColumnTypeClass::Binary + } + _ => ColumnTypeClass::Other, + } +} diff --git a/plugins/languages/sql/src/schema/expr.rs b/plugins/languages/sql/src/schema/expr.rs new file mode 100644 index 00000000..36fea83c --- /dev/null +++ b/plugins/languages/sql/src/schema/expr.rs @@ -0,0 +1,456 @@ +use std::collections::BTreeSet; + +use sqlparser::ast::{ + BinaryOperator, CaseWhen, Expr, Function, FunctionArg, FunctionArgExpr, FunctionArguments, + InTarget, Query, Spanned, UnaryOperator, Value, WindowType, +}; +use sqlparser::keywords::Keyword; +use sqlparser::tokenizer::{Token, TokenWithSpan}; + +use crate::schema::scope::{QueryScope, peel_nested}; +use crate::schema::types::ColumnTypeClass; + +pub(crate) trait ExprVisitor { + fn tokens(&self) -> &[TokenWithSpan]; + fn stmt_start_line(&self) -> u32; + fn record(&mut self, line: u32, rule: &'static str); + fn visit_subquery(&mut self, query: &Query, parent: &QueryScope<'_>); +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ClauseKind { + General, + Filter, + JoinOn, + OrderBy, +} + +impl ClauseKind { + fn fallback_keyword(self) -> Option { + match self { + ClauseKind::General => None, + ClauseKind::Filter => Some(Keyword::WHERE), + ClauseKind::JoinOn => Some(Keyword::ON), + ClauseKind::OrderBy => Some(Keyword::ORDER), + } + } +} + +#[derive(Clone, Copy)] +pub(crate) struct ExprContext<'a> { + pub(crate) scope: &'a QueryScope<'a>, + pub(crate) excluded: &'a BTreeSet, + pub(crate) clause: ClauseKind, +} + +impl<'a> ExprContext<'a> { + pub(crate) fn new( + scope: &'a QueryScope<'a>, + excluded: &'a BTreeSet, + clause: ClauseKind, + ) -> ExprContext<'a> { + ExprContext { + scope, + excluded, + clause, + } + } + + fn with_clause(self, clause: ClauseKind) -> ExprContext<'a> { + ExprContext { clause, ..self } + } +} + +pub(crate) fn check_expr(visitor: &mut V, expr: &Expr, ctx: ExprContext<'_>) { + match expr { + Expr::Identifier(_) | Expr::CompoundIdentifier(_) => { + check_column_ref(visitor, expr, ctx); + } + Expr::BinaryOp { left, op, right } => { + check_binary_op(visitor, expr, left, op, right, ctx); + } + Expr::Subquery(query) + | Expr::Exists { + subquery: query, .. + } => { + visitor.visit_subquery(query, ctx.scope); + } + _ => check_nested_expr(visitor, expr, ctx), + } +} + +fn check_column_ref(visitor: &mut V, expr: &Expr, ctx: ExprContext<'_>) { + let Some((table, col)) = ctx.scope.resolve_column_expr(expr, ctx.excluded) else { + return; + }; + let line = resolve_expr_line(visitor, expr, Some(&col), ctx.clause.fallback_keyword()); + if !table.columns.contains_key(&col) { + visitor.record(line, "unknown-column"); + return; + } + if table.is_indexed_column(&col) { + return; + } + match ctx.clause { + ClauseKind::General => {} + ClauseKind::Filter => visitor.record(line, "filter-on-unindexed-column"), + ClauseKind::JoinOn => { + visitor.record(line, "join-on-unindexed-column"); + visitor.record(line, "filter-on-unindexed-column"); + } + ClauseKind::OrderBy => visitor.record(line, "order-by-unindexed-column"), + } +} + +fn check_binary_op( + visitor: &mut V, + whole: &Expr, + left: &Expr, + op: &BinaryOperator, + right: &Expr, + ctx: ExprContext<'_>, +) { + if is_comparison_operator(op) { + check_text_compared_to_number(visitor, whole, left, right, ctx); + } + check_expr(visitor, left, ctx); + check_expr(visitor, right, ctx); +} + +fn check_text_compared_to_number( + visitor: &mut V, + whole: &Expr, + left: &Expr, + right: &Expr, + ctx: ExprContext<'_>, +) { + let matched_col = if is_bare_number_literal(right) { + resolve_text_column(left, ctx) + } else if is_bare_number_literal(left) { + resolve_text_column(right, ctx) + } else { + None + }; + if let Some(col) = matched_col { + let line = resolve_expr_line(visitor, whole, Some(&col), ctx.clause.fallback_keyword()); + visitor.record(line, "text-compared-to-number"); + } +} + +fn resolve_text_column(expr: &Expr, ctx: ExprContext<'_>) -> Option { + let (table, col) = ctx.scope.resolve_column_expr(expr, ctx.excluded)?; + (table.columns.get(&col).copied() == Some(ColumnTypeClass::Text)).then_some(col) +} + +fn check_nested_expr(visitor: &mut V, expr: &Expr, ctx: ExprContext<'_>) { + if let Some(inner) = unwrap_unary_expr(expr).or_else(|| unwrap_predicate_expr(expr)) { + check_expr(visitor, inner, ctx); + return; + } + if let Some((left, right)) = unwrap_binary_like_expr(expr) { + check_expr(visitor, left, ctx); + check_expr(visitor, right, ctx); + return; + } + check_composite_expr(visitor, expr, ctx); +} + +fn unwrap_unary_expr(expr: &Expr) -> Option<&Expr> { + match expr { + Expr::Nested(inner) + | Expr::UnaryOp { expr: inner, .. } + | Expr::Cast { expr: inner, .. } + | Expr::Convert { expr: inner, .. } + | Expr::Extract { expr: inner, .. } + | Expr::Ceil { expr: inner, .. } + | Expr::Floor { expr: inner, .. } + | Expr::Collate { expr: inner, .. } + | Expr::JsonAccess { value: inner, .. } + | Expr::CompoundFieldAccess { root: inner, .. } => Some(inner), + _ => None, + } +} + +fn unwrap_predicate_expr(expr: &Expr) -> Option<&Expr> { + if let Expr::IsNull(target) | Expr::IsNotNull(target) = expr { + return Some(target); + } + if let Expr::IsUnknown(target) | Expr::IsNotUnknown(target) = expr { + return Some(target); + } + match expr { + Expr::IsFalse(target) + | Expr::IsNotFalse(target) + | Expr::IsTrue(target) + | Expr::IsNotTrue(target) => Some(target), + _ => None, + } +} + +fn unwrap_binary_like_expr(expr: &Expr) -> Option<(&Expr, &Expr)> { + match expr { + Expr::IsDistinctFrom(lhs, rhs) + | Expr::IsNotDistinctFrom(lhs, rhs) + | Expr::AnyOp { + left: lhs, + right: rhs, + .. + } + | Expr::AllOp { + left: lhs, + right: rhs, + .. + } + | Expr::Like { + expr: lhs, + pattern: rhs, + .. + } + | Expr::ILike { + expr: lhs, + pattern: rhs, + .. + } + | Expr::SimilarTo { + expr: lhs, + pattern: rhs, + .. + } + | Expr::RLike { + expr: lhs, + pattern: rhs, + .. + } + | Expr::Position { + expr: lhs, + r#in: rhs, + } => Some((lhs, rhs)), + _ => None, + } +} + +fn check_composite_expr(visitor: &mut V, expr: &Expr, ctx: ExprContext<'_>) { + match expr { + Expr::Between { + expr: target, + low, + high, + .. + } => { + check_expr_list(visitor, [target.as_ref(), low.as_ref(), high.as_ref()], ctx); + } + Expr::Case { + operand, + conditions, + else_result, + .. + } => check_case( + visitor, + operand.as_deref(), + conditions, + else_result.as_deref(), + ctx, + ), + Expr::In { + expr: target_expr, + target, + .. + } => { + check_expr(visitor, target_expr, ctx); + check_in_target(visitor, target, ctx); + } + Expr::Function(func) => check_function(visitor, func, ctx), + Expr::Tuple(items) => check_expr_list(visitor, items.iter(), ctx), + Expr::Array(array) => check_expr_list(visitor, array.elem.iter(), ctx), + _ => check_string_expr(visitor, expr, ctx), + } +} + +fn check_string_expr(visitor: &mut V, expr: &Expr, ctx: ExprContext<'_>) { + match expr { + Expr::Substring { + expr: inner, + substring_from, + substring_for, + .. + } => { + let parts = [ + Some(inner.as_ref()), + substring_from.as_deref(), + substring_for.as_deref(), + ]; + check_expr_list(visitor, parts.into_iter().flatten(), ctx); + } + Expr::Trim { + expr: inner, + trim_what, + .. + } => { + let parts = [Some(inner.as_ref()), trim_what.as_deref()]; + check_expr_list(visitor, parts.into_iter().flatten(), ctx); + } + _ => {} + } +} + +fn check_expr_list<'a, V: ExprVisitor>( + visitor: &mut V, + exprs: impl IntoIterator, + ctx: ExprContext<'_>, +) { + for expr in exprs { + check_expr(visitor, expr, ctx); + } +} + +fn check_case( + visitor: &mut V, + operand: Option<&Expr>, + conditions: &[CaseWhen], + else_result: Option<&Expr>, + ctx: ExprContext<'_>, +) { + if let Some(op) = operand { + check_expr(visitor, op, ctx); + } + for when in conditions { + check_expr(visitor, &when.condition, ctx); + check_expr(visitor, &when.result, ctx); + } + if let Some(els) = else_result { + check_expr(visitor, els, ctx); + } +} + +fn check_in_target(visitor: &mut V, target: &InTarget, ctx: ExprContext<'_>) { + match target { + InTarget::List(items) => check_expr_list(visitor, items.iter(), ctx), + InTarget::Subquery(query) => visitor.visit_subquery(query, ctx.scope), + InTarget::Unnest(inner) => check_expr(visitor, inner, ctx), + InTarget::Table { .. } => {} + } +} + +fn check_function(visitor: &mut V, func: &Function, ctx: ExprContext<'_>) { + match &func.args { + FunctionArguments::Subquery(query) => visitor.visit_subquery(query, ctx.scope), + FunctionArguments::List(list) => { + for arg in &list.args { + check_function_arg(visitor, arg, ctx); + } + } + FunctionArguments::None => {} + } + let general = ctx.with_clause(ClauseKind::General); + if let Some(filter) = &func.filter { + check_expr(visitor, filter, general); + } + check_expr_list( + visitor, + func.within_group.iter().map(|order| &order.expr), + general, + ); + if let Some(WindowType::WindowSpec(spec)) = &func.over { + check_expr_list(visitor, spec.partition_by.iter(), general); + check_expr_list( + visitor, + spec.order_by.iter().map(|order| &order.expr), + general, + ); + } +} + +fn check_function_arg(visitor: &mut V, arg: &FunctionArg, ctx: ExprContext<'_>) { + let expr_slot = match arg { + FunctionArg::Unnamed(slot) => slot, + FunctionArg::Named { arg: slot, .. } => slot, + FunctionArg::ExprNamed { arg: slot, .. } => slot, + }; + if let FunctionArgExpr::Expr(expr) = expr_slot { + check_expr(visitor, expr, ctx); + } +} + +pub(crate) fn is_comparison_operator(op: &BinaryOperator) -> bool { + matches!( + op, + BinaryOperator::Eq + | BinaryOperator::NotEq + | BinaryOperator::Lt + | BinaryOperator::LtEq + | BinaryOperator::Gt + | BinaryOperator::GtEq + | BinaryOperator::Spaceship + ) +} + +pub(crate) fn is_bare_number_literal(expr: &Expr) -> bool { + match peel_nested(expr) { + Expr::Value(val) => matches!(val.value, Value::Number(_, _)), + Expr::UnaryOp { + op: UnaryOperator::Plus | UnaryOperator::Minus, + expr: inner, + } => matches!( + peel_nested(inner), + Expr::Value(val) if matches!(val.value, Value::Number(_, _)) + ), + _ => false, + } +} + +pub(crate) fn resolve_expr_line( + visitor: &V, + expr: &Expr, + ident_hint: Option<&str>, + keyword_hint: Option, +) -> u32 { + let span_line = expr.span().start.line as u32; + if span_line > 0 { + return span_line; + } + resolve_fallback_line( + visitor.tokens(), + visitor.stmt_start_line(), + ident_hint, + keyword_hint, + ) +} + +pub(crate) fn resolve_fallback_line( + tokens: &[TokenWithSpan], + stmt_start_line: u32, + ident_hint: Option<&str>, + keyword_hint: Option, +) -> u32 { + if let Some(name) = ident_hint + && let Some(line) = find_ident_line(tokens, name) + { + return line; + } + if let Some(keyword) = keyword_hint + && let Some(line) = find_keyword_line(tokens, keyword) + { + return line; + } + stmt_start_line +} + +fn find_ident_line(tokens: &[TokenWithSpan], target: &str) -> Option { + tokens.iter().find_map(|tok| match &tok.token { + Token::Word(word) if word.value.eq_ignore_ascii_case(target) => { + let line = tok.span.start.line as u32; + (line > 0).then_some(line) + } + _ => None, + }) +} + +fn find_keyword_line(tokens: &[TokenWithSpan], keyword: Keyword) -> Option { + tokens.iter().find_map(|tok| match &tok.token { + Token::Word(word) if word.keyword == keyword => { + let line = tok.span.start.line as u32; + (line > 0).then_some(line) + } + _ => None, + }) +} diff --git a/plugins/languages/sql/src/schema/rules.rs b/plugins/languages/sql/src/schema/rules.rs new file mode 100644 index 00000000..d9cfd1cb --- /dev/null +++ b/plugins/languages/sql/src/schema/rules.rs @@ -0,0 +1,602 @@ +use std::collections::BTreeSet; + +use codeint_model::HazardLine; +use sqlparser::ast::{ + AssignmentTarget, Delete, Expr, FromTable, GroupByExpr, Insert, Join, JoinConstraint, + JoinOperator, Merge, ObjectName, OrderBy, OrderByExpr, OrderByKind, Query, Select, SelectItem, + SetExpr, Spanned, Statement, TableFactor, TableObject, TableWithJoins, Update, + UpdateTableFromKind, +}; +use sqlparser::keywords::Keyword; +use sqlparser::tokenizer::TokenWithSpan; + +use crate::ParsedSqlStatement; +use crate::schema::expr::{ + ClauseKind, ExprContext, ExprVisitor, check_expr, resolve_fallback_line, +}; +use crate::schema::scope::{QueryScope, collect_select_aliases}; +use crate::schema::types::{ + SqlSchema, TableSchema, normalize_ident, object_name_last_ident, split_object_name, +}; + +const SCHEMA_RULES: &[&str] = &[ + "filter-on-unindexed-column", + "join-on-unindexed-column", + "order-by-unindexed-column", + "text-compared-to-number", + "unknown-column", +]; + +pub fn schema_hazard_rules() -> impl Iterator { + SCHEMA_RULES.iter().copied() +} + +pub fn collect_schema_hazards( + statements: &[ParsedSqlStatement], + schema: &SqlSchema, +) -> Vec { + if schema.is_empty() { + return Vec::new(); + } + let mut hits = BTreeSet::new(); + for parsed in statements { + let mut checker = SchemaRuleChecker { + schema, + tokens: &parsed.tokens, + stmt_start_line: parsed.start_line, + hits: &mut hits, + }; + checker.visit_statement(&parsed.statement); + } + hits.into_iter() + .map(|(line, rule)| HazardLine { + line, + rule: rule.to_owned(), + }) + .collect() +} + +struct SchemaRuleChecker<'a> { + schema: &'a SqlSchema, + tokens: &'a [TokenWithSpan], + stmt_start_line: u32, + hits: &'a mut BTreeSet<(u32, &'static str)>, +} + +impl ExprVisitor for SchemaRuleChecker<'_> { + fn tokens(&self) -> &[TokenWithSpan] { + self.tokens + } + + fn stmt_start_line(&self) -> u32 { + self.stmt_start_line + } + + fn record(&mut self, line: u32, rule: &'static str) { + let target = if line > 0 { line } else { self.stmt_start_line }; + self.hits.insert((target, rule)); + } + + fn visit_subquery(&mut self, query: &Query, parent: &QueryScope<'_>) { + self.visit_query_in_parent(query, parent); + } +} + +impl<'a> SchemaRuleChecker<'a> { + fn visit_statement(&mut self, stmt: &Statement) { + match stmt { + Statement::Query(query) => self.visit_query(query, BTreeSet::new()), + Statement::Explain { statement, .. } => self.visit_statement(statement), + Statement::Insert(insert) => self.visit_insert(insert), + Statement::Update(update) => self.visit_update(update), + Statement::Delete(delete) => self.visit_delete(delete), + Statement::Merge(merge) => self.visit_merge(merge), + Statement::CreateView(view) => self.visit_query(&view.query, BTreeSet::new()), + Statement::CreateTable(table) => { + if let Some(query) = &table.query { + self.visit_query(query, BTreeSet::new()); + } + } + _ => {} + } + } + + fn visit_insert(&mut self, insert: &Insert) { + if let TableObject::TableName(table_name) = &insert.table + && let Some((table_schema, name)) = split_object_name(table_name) + && let Some(table) = self.schema.get_table(table_schema.as_deref(), &name) + { + for col_obj in &insert.columns { + self.check_target_column(table, col_obj); + } + } + if let Some(source) = &insert.source { + self.visit_query(source, BTreeSet::new()); + } + } + + fn visit_update(&mut self, update: &Update) { + let mut scope = QueryScope::root(BTreeSet::new()); + scope.add_table_with_joins(&update.table, self.schema); + if let Some(from) = &update.from { + let from_tables = match from { + UpdateTableFromKind::BeforeSet(tables) | UpdateTableFromKind::AfterSet(tables) => { + tables + } + }; + for twj in from_tables { + scope.add_table_with_joins(twj, self.schema); + } + } + + let target_table = + self.resolve_single_factor_table(&update.table.relation, &scope.cte_names); + let empty = BTreeSet::new(); + self.visit_table_with_joins_subqueries(&update.table, &scope); + self.check_table_with_joins_conditions(&update.table, &scope); + + for assign in &update.assignments { + if let Some(table) = target_table { + self.check_assignment_target(table, &assign.target); + } + check_expr( + self, + &assign.value, + ExprContext::new(&scope, &empty, ClauseKind::General), + ); + } + self.check_dml_tail( + update.selection.as_ref(), + update.returning.as_deref(), + &update.order_by, + &scope, + ); + } + + fn visit_delete(&mut self, delete: &Delete) { + let mut scope = QueryScope::root(BTreeSet::new()); + let from_tables = match &delete.from { + FromTable::WithFromKeyword(tables) | FromTable::WithoutKeyword(tables) => tables, + }; + for twj in from_tables { + scope.add_table_with_joins(twj, self.schema); + } + if let Some(using) = &delete.using { + for twj in using { + scope.add_table_with_joins(twj, self.schema); + } + } + for twj in from_tables { + self.visit_table_with_joins_subqueries(twj, &scope); + self.check_table_with_joins_conditions(twj, &scope); + } + self.check_dml_tail( + delete.selection.as_ref(), + delete.returning.as_deref(), + &delete.order_by, + &scope, + ); + } + + fn check_dml_tail( + &mut self, + selection: Option<&Expr>, + returning: Option<&[SelectItem]>, + order_by: &[OrderByExpr], + scope: &QueryScope<'_>, + ) { + let empty = BTreeSet::new(); + if let Some(filter) = selection { + check_expr( + self, + filter, + ExprContext::new(scope, &empty, ClauseKind::Filter), + ); + } + if let Some(items) = returning { + self.check_select_items(items, scope, &empty); + } + self.check_order_by_exprs(order_by, scope, &empty); + } + + fn visit_merge(&mut self, merge: &Merge) { + let mut scope = QueryScope::root(BTreeSet::new()); + scope.add_table_factor(&merge.table, self.schema); + scope.add_table_factor(&merge.source, self.schema); + let empty = BTreeSet::new(); + self.visit_table_factor_subqueries(&merge.table, &scope); + self.visit_table_factor_subqueries(&merge.source, &scope); + check_expr( + self, + &merge.on, + ExprContext::new(&scope, &empty, ClauseKind::JoinOn), + ); + for clause in &merge.clauses { + if let Some(predicate) = &clause.predicate { + check_expr( + self, + predicate, + ExprContext::new(&scope, &empty, ClauseKind::Filter), + ); + } + } + } + + fn visit_query(&mut self, query: &Query, outer_ctes: BTreeSet) { + let cte_names = self.collect_and_visit_ctes(query, outer_ctes); + self.visit_set_expr(&query.body, query.order_by.as_ref(), cte_names, None); + } + + fn visit_query_in_parent(&mut self, query: &Query, parent: &QueryScope<'_>) { + let cte_names = self.collect_and_visit_ctes(query, parent.cte_names.clone()); + self.visit_set_expr( + &query.body, + query.order_by.as_ref(), + cte_names, + Some(parent), + ); + } + + fn collect_and_visit_ctes( + &mut self, + query: &Query, + mut cte_names: BTreeSet, + ) -> BTreeSet { + if let Some(with) = &query.with { + for cte in &with.cte_tables { + let name = normalize_ident(&cte.alias.name); + let mut visible = cte_names.clone(); + if with.recursive { + visible.insert(name.clone()); + } + self.visit_query(&cte.query, visible); + cte_names.insert(name); + } + } + cte_names + } + + fn visit_set_expr( + &mut self, + set_expr: &SetExpr, + order_by: Option<&OrderBy>, + cte_names: BTreeSet, + parent: Option<&QueryScope<'_>>, + ) { + match set_expr { + SetExpr::Select(select) => { + self.visit_select(select, order_by, cte_names, parent); + } + SetExpr::Query(inner) => match parent { + Some(p) => self.visit_query_in_parent(inner, p), + None => self.visit_query(inner, cte_names), + }, + SetExpr::SetOperation { left, right, .. } => { + self.visit_set_expr(left, None, cte_names.clone(), parent); + self.visit_set_expr(right, None, cte_names, parent); + } + SetExpr::Insert(stmt) + | SetExpr::Update(stmt) + | SetExpr::Delete(stmt) + | SetExpr::Merge(stmt) => self.visit_statement(stmt), + _ => {} + } + } + + fn visit_select( + &mut self, + select: &Select, + order_by: Option<&OrderBy>, + cte_names: BTreeSet, + parent: Option<&QueryScope<'_>>, + ) { + let mut scope = match parent { + Some(p) => { + let mut child = p.child(); + child.cte_names = cte_names; + child + } + None => QueryScope::root(cte_names), + }; + for twj in &select.from { + scope.add_table_with_joins(twj, self.schema); + } + + let empty = BTreeSet::new(); + let select_aliases = collect_select_aliases(&select.projection); + + for twj in &select.from { + self.visit_table_with_joins_subqueries(twj, &scope); + self.check_table_with_joins_conditions(twj, &scope); + } + self.check_select_items(&select.projection, &scope, &empty); + if let Some(prewhere) = &select.prewhere { + check_expr( + self, + prewhere, + ExprContext::new(&scope, &empty, ClauseKind::Filter), + ); + } + if let Some(selection) = &select.selection { + check_expr( + self, + selection, + ExprContext::new(&scope, &empty, ClauseKind::Filter), + ); + } + self.check_select_post_clauses(select, order_by, &scope, &select_aliases); + } + + fn check_select_post_clauses( + &mut self, + select: &Select, + order_by: Option<&OrderBy>, + scope: &QueryScope<'_>, + select_aliases: &BTreeSet, + ) { + if let GroupByExpr::Expressions(exprs, _) = &select.group_by { + let ctx = ExprContext::new(scope, select_aliases, ClauseKind::General); + for expr in exprs { + check_expr(self, expr, ctx); + } + } + if let Some(having) = &select.having { + check_expr( + self, + having, + ExprContext::new(scope, select_aliases, ClauseKind::General), + ); + } + if let Some(qualify) = &select.qualify { + check_expr( + self, + qualify, + ExprContext::new(scope, select_aliases, ClauseKind::General), + ); + } + if let Some(order) = order_by + && let OrderByKind::Expressions(exprs) = &order.kind + { + self.check_order_by_exprs(exprs, scope, select_aliases); + } + } + + fn check_select_items( + &mut self, + items: &[SelectItem], + scope: &QueryScope<'_>, + excluded: &BTreeSet, + ) { + let ctx = ExprContext::new(scope, excluded, ClauseKind::General); + for item in items { + match item { + SelectItem::UnnamedExpr(expr) + | SelectItem::ExprWithAlias { expr, .. } + | SelectItem::ExprWithAliases { expr, .. } => { + check_expr(self, expr, ctx); + } + SelectItem::QualifiedWildcard(_, _) | SelectItem::Wildcard(_) => {} + } + } + } + + fn check_order_by_exprs( + &mut self, + exprs: &[OrderByExpr], + scope: &QueryScope<'_>, + excluded: &BTreeSet, + ) { + let ctx = ExprContext::new(scope, excluded, ClauseKind::OrderBy); + for order_expr in exprs { + check_expr(self, &order_expr.expr, ctx); + } + } + + fn visit_table_with_joins_subqueries(&mut self, twj: &TableWithJoins, scope: &QueryScope<'_>) { + self.visit_table_factor_subqueries(&twj.relation, scope); + for join in &twj.joins { + self.visit_table_factor_subqueries(&join.relation, scope); + } + } + + fn visit_table_factor_subqueries(&mut self, factor: &TableFactor, scope: &QueryScope<'_>) { + match factor { + TableFactor::Derived { + lateral, subquery, .. + } => { + if *lateral { + self.visit_query_in_parent(subquery, scope); + } else { + self.visit_query(subquery, scope.cte_names.clone()); + } + } + TableFactor::NestedJoin { + table_with_joins, .. + } => self.visit_table_with_joins_subqueries(table_with_joins, scope), + _ => {} + } + } + + fn check_table_with_joins_conditions(&mut self, twj: &TableWithJoins, scope: &QueryScope<'_>) { + if let TableFactor::NestedJoin { + table_with_joins, .. + } = &twj.relation + { + self.check_table_with_joins_conditions(table_with_joins, scope); + } + let mut left_scope = QueryScope::root(scope.cte_names.clone()); + left_scope.add_table_factor(&twj.relation, self.schema); + for join in &twj.joins { + if let TableFactor::NestedJoin { + table_with_joins, .. + } = &join.relation + { + self.check_table_with_joins_conditions(table_with_joins, scope); + } + self.check_join(join, &left_scope, scope); + left_scope.add_table_factor(&join.relation, self.schema); + } + } + + fn check_join( + &mut self, + join: &Join, + left_scope: &QueryScope<'_>, + full_scope: &QueryScope<'_>, + ) { + let empty = BTreeSet::new(); + match &join.join_operator { + JoinOperator::Join(constraint) + | JoinOperator::Inner(constraint) + | JoinOperator::Left(constraint) + | JoinOperator::LeftOuter(constraint) + | JoinOperator::Right(constraint) + | JoinOperator::RightOuter(constraint) + | JoinOperator::FullOuter(constraint) + | JoinOperator::CrossJoin(constraint) + | JoinOperator::Semi(constraint) + | JoinOperator::LeftSemi(constraint) + | JoinOperator::RightSemi(constraint) + | JoinOperator::Anti(constraint) + | JoinOperator::LeftAnti(constraint) + | JoinOperator::RightAnti(constraint) => { + self.check_join_constraint(constraint, &join.relation, left_scope, full_scope); + } + JoinOperator::AsOf { + match_condition, + constraint, + } => { + check_expr( + self, + match_condition, + ExprContext::new(full_scope, &empty, ClauseKind::JoinOn), + ); + self.check_join_constraint(constraint, &join.relation, left_scope, full_scope); + } + _ => {} + } + } + + fn check_join_constraint( + &mut self, + constraint: &JoinConstraint, + right_relation: &TableFactor, + left_scope: &QueryScope<'_>, + full_scope: &QueryScope<'_>, + ) { + let empty = BTreeSet::new(); + match constraint { + JoinConstraint::On(expr) => { + check_expr( + self, + expr, + ExprContext::new(full_scope, &empty, ClauseKind::JoinOn), + ); + } + JoinConstraint::Using(columns) | JoinConstraint::UsingAlias(columns, _) => { + let right_table = + self.resolve_single_factor_table(right_relation, &full_scope.cte_names); + for col_obj in columns { + self.check_using_column(col_obj, left_scope, right_table); + } + } + JoinConstraint::Natural | JoinConstraint::None => {} + } + } + + fn check_using_column( + &mut self, + col_obj: &ObjectName, + left_scope: &QueryScope<'_>, + right_table: Option<&TableSchema>, + ) { + let Some(col) = object_name_last_ident(col_obj) else { + return; + }; + let line = self.resolve_object_name_line(col_obj, &col, Some(Keyword::USING)); + if let Some(table) = right_table { + self.check_join_column_on_table(table, &col, line); + } + if !left_scope.has_unknown_binding() { + let left_matches: Vec<&TableSchema> = left_scope + .bindings + .iter() + .filter_map(|b| b.table) + .filter(|t| t.columns.contains_key(&col)) + .collect(); + if left_matches.len() == 1 { + self.check_join_column_on_table(left_matches[0], &col, line); + } else if left_matches.is_empty() + && left_scope.bindings.len() == 1 + && left_scope.bindings[0].table.is_some() + { + self.record(line, "unknown-column"); + } + } + } + + fn check_join_column_on_table(&mut self, table: &TableSchema, col: &str, line: u32) { + if !table.columns.contains_key(col) { + self.record(line, "unknown-column"); + } else if !table.is_indexed_column(col) { + self.record(line, "join-on-unindexed-column"); + } + } + + fn check_assignment_target(&mut self, table: &TableSchema, target: &AssignmentTarget) { + match target { + AssignmentTarget::ColumnName(col_obj) => self.check_target_column(table, col_obj), + AssignmentTarget::Tuple(cols) => { + for col_obj in cols { + self.check_target_column(table, col_obj); + } + } + } + } + + fn check_target_column(&mut self, table: &TableSchema, col_obj: &ObjectName) { + let Some(col) = object_name_last_ident(col_obj) else { + return; + }; + if !table.columns.contains_key(&col) { + let line = self.resolve_object_name_line(col_obj, &col, None); + self.record(line, "unknown-column"); + } + } + + fn resolve_single_factor_table( + &self, + factor: &TableFactor, + cte_names: &BTreeSet, + ) -> Option<&'a TableSchema> { + let TableFactor::Table { + name, args: None, .. + } = factor + else { + return None; + }; + let (table_schema, table_name) = split_object_name(name)?; + if table_schema.is_none() && cte_names.contains(&table_name) { + return None; + } + self.schema.get_table(table_schema.as_deref(), &table_name) + } + + fn resolve_object_name_line( + &self, + obj: &ObjectName, + ident_hint: &str, + keyword_hint: Option, + ) -> u32 { + let span_line = obj.span().start.line as u32; + if span_line > 0 { + return span_line; + } + resolve_fallback_line( + self.tokens, + self.stmt_start_line, + Some(ident_hint), + keyword_hint, + ) + } +} diff --git a/plugins/languages/sql/src/schema/scope.rs b/plugins/languages/sql/src/schema/scope.rs new file mode 100644 index 00000000..0945df7c --- /dev/null +++ b/plugins/languages/sql/src/schema/scope.rs @@ -0,0 +1,304 @@ +use std::collections::BTreeSet; + +use sqlparser::ast::{Expr, Ident, ObjectName, SelectItem, TableFactor, TableWithJoins}; + +use crate::schema::types::{SqlSchema, TableSchema, normalize_ident, split_object_name}; + +const SYSTEM_COLUMNS: &[&str] = &[ + "_rowid_", "cmax", "cmin", "ctid", "oid", "rowid", "tableoid", "xmax", "xmin", +]; + +#[derive(Clone, Debug)] +pub(crate) struct TableBinding<'a> { + pub(crate) schema: Option, + pub(crate) table_name: Option, + pub(crate) alias: Option, + pub(crate) table: Option<&'a TableSchema>, +} + +impl<'a> TableBinding<'a> { + fn matches_qualifier(&self, qualifier: &str) -> bool { + if let Some(alias) = &self.alias { + return alias == qualifier; + } + self.table_name.as_deref() == Some(qualifier) + } + + fn matches_schema_table(&self, schema: &str, table: &str) -> bool { + self.alias.is_none() + && self.schema.as_deref() == Some(schema) + && self.table_name.as_deref() == Some(table) + } +} + +#[derive(Clone, Debug)] +pub(crate) struct QueryScope<'a> { + pub(crate) bindings: Vec>, + pub(crate) cte_names: BTreeSet, + pub(crate) parent: Option<&'a QueryScope<'a>>, +} + +impl<'a> QueryScope<'a> { + pub(crate) fn root(cte_names: BTreeSet) -> QueryScope<'a> { + QueryScope { + bindings: Vec::new(), + cte_names, + parent: None, + } + } + + pub(crate) fn child(&'a self) -> QueryScope<'a> { + QueryScope { + bindings: Vec::new(), + cte_names: self.cte_names.clone(), + parent: Some(self), + } + } + + pub(crate) fn add_table_with_joins(&mut self, twj: &TableWithJoins, sql_schema: &'a SqlSchema) { + self.add_table_factor(&twj.relation, sql_schema); + for join in &twj.joins { + self.add_table_factor(&join.relation, sql_schema); + } + } + + pub(crate) fn add_table_factor(&mut self, factor: &TableFactor, sql_schema: &'a SqlSchema) { + match factor { + TableFactor::Table { + name, alias, args, .. + } => { + let alias_name = alias.as_ref().map(|a| normalize_ident(&a.name)); + if args.is_some() { + self.bindings.push(TableBinding { + schema: None, + table_name: None, + alias: alias_name, + table: None, + }); + return; + } + self.add_named_table(name, alias_name, sql_schema); + } + TableFactor::Derived { alias, .. } => { + self.bindings.push(TableBinding { + schema: None, + table_name: None, + alias: alias.as_ref().map(|a| normalize_ident(&a.name)), + table: None, + }); + } + TableFactor::NestedJoin { + table_with_joins, .. + } => { + self.add_table_with_joins(table_with_joins, sql_schema); + } + _ => { + self.bindings.push(TableBinding { + schema: None, + table_name: None, + alias: None, + table: None, + }); + } + } + } + + pub(crate) fn add_named_table( + &mut self, + name: &ObjectName, + alias: Option, + sql_schema: &'a SqlSchema, + ) { + let Some((table_schema, table_name)) = split_object_name(name) else { + self.bindings.push(TableBinding { + schema: None, + table_name: None, + alias, + table: None, + }); + return; + }; + let is_cte = table_schema.is_none() && self.cte_names.contains(&table_name); + let resolved = if is_cte { + None + } else { + sql_schema.get_table(table_schema.as_deref(), &table_name) + }; + self.bindings.push(TableBinding { + schema: table_schema, + table_name: Some(table_name), + alias, + table: resolved, + }); + } + + pub(crate) fn resolve_column_expr( + &self, + expr: &Expr, + excluded_names: &BTreeSet, + ) -> Option<(&'a TableSchema, String)> { + match peel_nested(expr) { + Expr::Identifier(ident) => self.resolve_unqualified(ident, excluded_names), + Expr::CompoundIdentifier(idents) => self.resolve_qualified(idents), + _ => None, + } + } + + pub(crate) fn resolve_unqualified( + &self, + ident: &Ident, + excluded_names: &BTreeSet, + ) -> Option<(&'a TableSchema, String)> { + let col = normalize_ident(ident); + if excluded_names.contains(&col) || is_system_column(&col) { + return None; + } + if let Some(found) = self.resolve_known_column_in_chain(&col) { + return Some((found, col)); + } + self.resolve_single_unambiguous_table() + .map(|table| (table, col)) + } + + fn resolve_known_column_in_chain(&self, col: &str) -> Option<&'a TableSchema> { + let mut cursor = Some(self); + while let Some(scope) = cursor { + if !scope.bindings.is_empty() { + if scope.has_unknown_binding() { + return None; + } + let matches: Vec<&'a TableSchema> = scope + .bindings + .iter() + .filter_map(|b| b.table) + .filter(|t| t.columns.contains_key(col)) + .collect(); + if matches.len() == 1 { + return Some(matches[0]); + } + if matches.len() > 1 { + return None; + } + } + cursor = scope.parent; + } + None + } + + fn resolve_single_unambiguous_table(&self) -> Option<&'a TableSchema> { + let mut known_table: Option<&'a TableSchema> = None; + let mut total_tables = 0usize; + let mut cursor = Some(self); + while let Some(scope) = cursor { + if scope.has_unknown_binding() { + return None; + } + for binding in &scope.bindings { + total_tables += 1; + if total_tables > 1 { + return None; + } + known_table = binding.table; + } + cursor = scope.parent; + } + known_table + } + + pub(crate) fn resolve_qualified(&self, idents: &[Ident]) -> Option<(&'a TableSchema, String)> { + match idents { + [qual, col] => { + let q = normalize_ident(qual); + let c = normalize_ident(col); + if is_system_column(&c) { + return None; + } + self.lookup_by_qualifier(&q).map(|table| (table, c)) + } + [schema, table, col] => { + let s = normalize_ident(schema); + let t = normalize_ident(table); + let c = normalize_ident(col); + if is_system_column(&c) { + return None; + } + self.lookup_by_schema_table(&s, &t).map(|ts| (ts, c)) + } + _ => None, + } + } + + fn lookup_by_qualifier(&self, qualifier: &str) -> Option<&'a TableSchema> { + let mut cursor = Some(self); + while let Some(scope) = cursor { + let matches: Vec<&TableBinding<'a>> = scope + .bindings + .iter() + .filter(|b| b.matches_qualifier(qualifier)) + .collect(); + if matches.len() == 1 { + return matches[0].table; + } + if matches.len() > 1 { + return None; + } + cursor = scope.parent; + } + None + } + + fn lookup_by_schema_table(&self, schema: &str, table: &str) -> Option<&'a TableSchema> { + let mut cursor = Some(self); + while let Some(scope) = cursor { + let matches: Vec<&TableBinding<'a>> = scope + .bindings + .iter() + .filter(|b| b.matches_schema_table(schema, table)) + .collect(); + if matches.len() == 1 { + return matches[0].table; + } + if matches.len() > 1 { + return None; + } + cursor = scope.parent; + } + None + } + + pub(crate) fn has_unknown_binding(&self) -> bool { + self.bindings.iter().any(|b| b.table.is_none()) + } +} + +pub(crate) fn peel_nested(mut expr: &Expr) -> &Expr { + while let Expr::Nested(inner) = expr { + expr = inner; + } + expr +} + +pub(crate) fn collect_select_aliases(projection: &[SelectItem]) -> BTreeSet { + let mut aliases = BTreeSet::new(); + for item in projection { + match item { + SelectItem::ExprWithAlias { alias, .. } => { + aliases.insert(normalize_ident(alias)); + } + SelectItem::ExprWithAliases { + aliases: item_aliases, + .. + } => { + for alias in item_aliases { + aliases.insert(normalize_ident(alias)); + } + } + _ => {} + } + } + aliases +} + +pub(crate) fn is_system_column(col: &str) -> bool { + SYSTEM_COLUMNS.binary_search(&col).is_ok() +} diff --git a/plugins/languages/sql/src/schema/tests.rs b/plugins/languages/sql/src/schema/tests.rs new file mode 100644 index 00000000..8647e20d --- /dev/null +++ b/plugins/languages/sql/src/schema/tests.rs @@ -0,0 +1,305 @@ +use codeint_model::RepoPath; + +use crate::schema::{ColumnTypeClass, IndexSchema, SqlSchema}; +use crate::{ParsedSqlStatement, Sql, SqlDialect}; + +fn parse_sql(dialect: SqlDialect, source: &str) -> Vec { + let path = RepoPath::new("migrations/001.sql").expect("valid path"); + Sql::with_dialect(dialect) + .lower_with_details(&path, source) + .expect("lower succeeds") + .parsed_statements +} + +#[test] +fn creates_table_with_normalized_columns_and_type_classes() { + let stmts = parse_sql( + SqlDialect::Postgresql, + r#" + CREATE TABLE Users ( + Id BIGSERIAL PRIMARY KEY, + Email VARCHAR(255) UNIQUE, + Bio TEXT, + Handle CITEXT, + Code CHARACTER VARYING(16), + Price NUMERIC(10, 2), + Balance MONEY, + Active BOOLEAN, + CreatedAt TIMESTAMP, + UpdatedDate DATE, + Avatar BYTEA, + Payload JSONB, + ExternalId UUID + ); + "#, + ); + let schema = SqlSchema::build([stmts.as_slice()]); + assert_eq!(schema.table_count(), 1); + assert!(!schema.is_empty()); + + let table = schema.get_table(None, "USERS").expect("table exists"); + assert_eq!(table.name, "users"); + assert_eq!(table.schema, None); + assert_eq!(table.primary_key, vec!["id"]); + assert_eq!( + table.indexes, + vec![IndexSchema { + name: None, + columns: vec!["email".to_owned()], + }] + ); + assert_eq!(table.column_type("id"), Some(ColumnTypeClass::Numeric)); + assert_eq!(table.column_type("email"), Some(ColumnTypeClass::Text)); + assert_eq!(table.column_type("bio"), Some(ColumnTypeClass::Text)); + assert_eq!(table.column_type("handle"), Some(ColumnTypeClass::Text)); + assert_eq!(table.column_type("code"), Some(ColumnTypeClass::Text)); + assert_eq!(table.column_type("price"), Some(ColumnTypeClass::Numeric)); + assert_eq!(table.column_type("balance"), Some(ColumnTypeClass::Numeric)); + assert_eq!(table.column_type("active"), Some(ColumnTypeClass::Boolean)); + assert_eq!( + table.column_type("createdat"), + Some(ColumnTypeClass::Temporal) + ); + assert_eq!( + table.column_type("updateddate"), + Some(ColumnTypeClass::Temporal) + ); + assert_eq!(table.column_type("avatar"), Some(ColumnTypeClass::Binary)); + assert_eq!(table.column_type("payload"), Some(ColumnTypeClass::Other)); + assert_eq!( + table.column_type("externalid"), + Some(ColumnTypeClass::Other) + ); +} + +#[test] +fn classifies_mysql_text_numeric_temporal_and_binary_types() { + let stmts = parse_sql( + SqlDialect::Mysql, + r#" + CREATE TABLE articles ( + id INT UNSIGNED PRIMARY KEY, + tiny_body TINYTEXT, + med_body MEDIUMTEXT, + long_body LONGTEXT, + raw_bin VARBINARY(64), + blob_data BLOB, + published_at DATETIME, + score DOUBLE, + flags TINYINT, + INDEX idx_pub_score (published_at, score), + KEY idx_flags (flags) + ); + "#, + ); + let schema = SqlSchema::build([stmts.as_slice()]); + let table = schema.get_table(None, "articles").expect("table exists"); + assert_eq!(table.column_type("id"), Some(ColumnTypeClass::Numeric)); + assert_eq!(table.column_type("tiny_body"), Some(ColumnTypeClass::Text)); + assert_eq!(table.column_type("med_body"), Some(ColumnTypeClass::Text)); + assert_eq!(table.column_type("long_body"), Some(ColumnTypeClass::Text)); + assert_eq!(table.column_type("raw_bin"), Some(ColumnTypeClass::Binary)); + assert_eq!( + table.column_type("blob_data"), + Some(ColumnTypeClass::Binary) + ); + assert_eq!( + table.column_type("published_at"), + Some(ColumnTypeClass::Temporal) + ); + assert_eq!(table.column_type("score"), Some(ColumnTypeClass::Numeric)); + assert_eq!(table.column_type("flags"), Some(ColumnTypeClass::Numeric)); + assert_eq!(table.indexes.len(), 2); + assert_eq!( + table.indexes[0], + IndexSchema { + name: Some("idx_pub_score".to_owned()), + columns: vec!["published_at".to_owned(), "score".to_owned()], + } + ); + assert_eq!( + table.indexes[1], + IndexSchema { + name: Some("idx_flags".to_owned()), + columns: vec!["flags".to_owned()], + } + ); +} + +#[test] +fn records_table_level_primary_key_unique_and_standalone_indexes_in_order() { + let stmts = parse_sql( + SqlDialect::Generic, + r#" + CREATE TABLE orders ( + tenant_id INT NOT NULL, + order_id INT NOT NULL, + customer_id INT NOT NULL, + created_at TIMESTAMP NOT NULL, + status VARCHAR(32) NOT NULL, + PRIMARY KEY (tenant_id, order_id), + CONSTRAINT uq_customer_created UNIQUE (customer_id, created_at) + ); + CREATE INDEX idx_orders_status_created ON orders (status DESC, created_at ASC); + CREATE UNIQUE INDEX idx_missing_table ON ghost_table (col_a); + "#, + ); + let schema = SqlSchema::build([stmts.as_slice()]); + assert_eq!(schema.table_count(), 1); + let table = schema.get_table(None, "orders").expect("orders exists"); + assert_eq!(table.primary_key, vec!["tenant_id", "order_id"]); + assert_eq!( + table.indexes, + vec![ + IndexSchema { + name: Some("uq_customer_created".to_owned()), + columns: vec!["customer_id".to_owned(), "created_at".to_owned()], + }, + IndexSchema { + name: Some("idx_orders_status_created".to_owned()), + columns: vec!["status".to_owned(), "created_at".to_owned()], + }, + ] + ); + assert!(table.is_indexed_column("tenant_id")); + assert!(!table.is_indexed_column("order_id")); + assert!(table.is_indexed_column("customer_id")); + assert!(!table.is_indexed_column("created_at")); + assert!(table.is_indexed_column("status")); +} + +#[test] +fn alters_table_add_rename_drop_columns_constraints_and_table_rename() { + let migration_1 = parse_sql( + SqlDialect::Postgresql, + r#" + CREATE TABLE app.accounts ( + id INT PRIMARY KEY, + email TEXT NOT NULL, + legacy_code VARCHAR(20) + ); + CREATE INDEX idx_accounts_email ON app.accounts (email); + "#, + ); + let migration_2 = parse_sql( + SqlDialect::Postgresql, + r#" + ALTER TABLE app.accounts ADD COLUMN region TEXT; + ALTER TABLE app.accounts RENAME COLUMN email TO primary_email; + ALTER TABLE app.accounts DROP COLUMN legacy_code; + ALTER TABLE app.accounts ADD CONSTRAINT uq_region UNIQUE (region); + "#, + ); + let migration_3 = parse_sql( + SqlDialect::Postgresql, + r#" + ALTER TABLE app.accounts DROP CONSTRAINT uq_region; + ALTER TABLE app.accounts RENAME TO members; + "#, + ); + + let schema = SqlSchema::build([ + migration_1.as_slice(), + migration_2.as_slice(), + migration_3.as_slice(), + ]); + assert_eq!(schema.table_count(), 1); + assert!(schema.get_table(Some("app"), "accounts").is_none()); + + let table = schema + .get_table(Some("app"), "members") + .expect("renamed table exists in same schema"); + assert!(table.has_column("id")); + assert!(table.has_column("primary_email")); + assert!(!table.has_column("email")); + assert!(!table.has_column("legacy_code")); + assert!(table.has_column("region")); + assert_eq!( + table.indexes, + vec![IndexSchema { + name: Some("idx_accounts_email".to_owned()), + columns: vec!["primary_email".to_owned()], + }] + ); +} + +#[test] +fn drops_tables_and_indexes_and_later_files_override_earlier_ones() { + let v1 = parse_sql( + SqlDialect::Generic, + r#" + CREATE TABLE items ( + id INT PRIMARY KEY, + sku TEXT NOT NULL, + notes TEXT + ); + CREATE INDEX idx_items_sku ON items (sku); + CREATE TABLE temp_staging ( + id INT PRIMARY KEY + ); + "#, + ); + let v2 = parse_sql( + SqlDialect::Generic, + r#" + DROP INDEX idx_items_sku; + DROP TABLE IF EXISTS temp_staging; + "#, + ); + let v3 = parse_sql( + SqlDialect::Generic, + r#" + CREATE TABLE items ( + id INT PRIMARY KEY, + sku INT NOT NULL + ); + "#, + ); + + let after_v2 = SqlSchema::build([v1.as_slice(), v2.as_slice()]); + assert_eq!(after_v2.table_count(), 1); + assert!(after_v2.get_table(None, "temp_staging").is_none()); + let items_v2 = after_v2.get_table(None, "items").expect("items exists"); + assert!(items_v2.indexes.is_empty()); + assert_eq!(items_v2.column_type("sku"), Some(ColumnTypeClass::Text)); + + let after_v3 = SqlSchema::build([v1.as_slice(), v2.as_slice(), v3.as_slice()]); + let items_v3 = after_v3.get_table(None, "items").expect("items replaced"); + assert_eq!(items_v3.column_type("sku"), Some(ColumnTypeClass::Numeric)); + assert!(!items_v3.has_column("notes")); +} + +#[test] +fn drops_mysql_index_on_table_and_handles_multi_schema_lookup() { + let mysql_stmts = parse_sql( + SqlDialect::Mysql, + r#" + CREATE TABLE events ( + id BIGINT PRIMARY KEY, + kind VARCHAR(32) + ); + CREATE INDEX idx_events_kind ON events (kind); + DROP INDEX idx_events_kind ON events; + "#, + ); + let mysql_schema = SqlSchema::build([mysql_stmts.as_slice()]); + let events = mysql_schema + .get_table(None, "events") + .expect("events exists"); + assert!(events.indexes.is_empty()); + + let multi_schema_stmts = parse_sql( + SqlDialect::Postgresql, + r#" + CREATE TABLE auth.users (id INT PRIMARY KEY); + CREATE TABLE billing.users (id INT PRIMARY KEY); + CREATE TABLE analytics.events (id INT PRIMARY KEY); + "#, + ); + let multi = SqlSchema::build([multi_schema_stmts.as_slice()]); + assert_eq!(multi.table_count(), 3); + assert!(multi.get_table(Some("auth"), "users").is_some()); + assert!(multi.get_table(Some("billing"), "users").is_some()); + assert!(multi.get_table(None, "users").is_none()); + assert!(multi.get_table(None, "events").is_some()); +} diff --git a/plugins/languages/sql/src/schema/types.rs b/plugins/languages/sql/src/schema/types.rs new file mode 100644 index 00000000..df75a100 --- /dev/null +++ b/plugins/languages/sql/src/schema/types.rs @@ -0,0 +1,114 @@ +use std::collections::BTreeMap; + +use sqlparser::ast::{Ident, ObjectName}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum ColumnTypeClass { + Text, + Numeric, + Boolean, + Temporal, + Binary, + Other, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IndexSchema { + pub name: Option, + pub columns: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TableSchema { + pub schema: Option, + pub name: String, + pub columns: BTreeMap, + pub primary_key: Vec, + pub indexes: Vec, +} + +impl TableSchema { + pub fn has_column(&self, column: &str) -> bool { + self.columns.contains_key(&column.to_ascii_lowercase()) + } + + pub fn column_type(&self, column: &str) -> Option { + self.columns.get(&column.to_ascii_lowercase()).copied() + } + + pub fn is_indexed_column(&self, column: &str) -> bool { + let lower = column.to_ascii_lowercase(); + self.primary_key.first().map(String::as_str) == Some(lower.as_str()) + || self + .indexes + .iter() + .any(|idx| idx.columns.first().map(String::as_str) == Some(lower.as_str())) + } +} + +pub(crate) type TableKey = (Option, String); + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct SqlSchema { + pub(crate) tables: BTreeMap, +} + +impl SqlSchema { + pub fn table_count(&self) -> usize { + self.tables.len() + } + + pub fn is_empty(&self) -> bool { + self.tables.is_empty() + } + + pub fn get_table(&self, schema: Option<&str>, name: &str) -> Option<&TableSchema> { + let key = self.resolve_table_key(schema, name)?; + self.tables.get(&key) + } + + pub(crate) fn resolve_table_key(&self, schema: Option<&str>, name: &str) -> Option { + let norm_schema = schema.map(str::to_ascii_lowercase); + let norm_name = name.to_ascii_lowercase(); + let exact = (norm_schema.clone(), norm_name.clone()); + if self.tables.contains_key(&exact) { + return Some(exact); + } + if norm_schema.is_some() { + return None; + } + let mut matches = self + .tables + .keys() + .filter(|(_, table_name)| table_name == &norm_name); + let first = matches.next()?; + if matches.next().is_some() { + return None; + } + Some(first.clone()) + } +} + +pub(crate) fn normalize_ident(ident: &Ident) -> String { + ident.value.to_ascii_lowercase() +} + +pub(crate) fn split_object_name(name: &ObjectName) -> Option<(Option, String)> { + let parts: Vec = name + .0 + .iter() + .filter_map(|part| part.as_ident().map(normalize_ident)) + .collect(); + match parts.as_slice() { + [] => None, + [table] => Some((None, table.clone())), + [.., schema, table] => Some((Some(schema.clone()), table.clone())), + } +} + +pub(crate) fn object_name_last_ident(name: &ObjectName) -> Option { + name.0 + .last() + .and_then(|part| part.as_ident()) + .map(normalize_ident) +} diff --git a/plugins/languages/sql/tests/schema_rules.rs b/plugins/languages/sql/tests/schema_rules.rs new file mode 100644 index 00000000..4539c6c9 --- /dev/null +++ b/plugins/languages/sql/tests/schema_rules.rs @@ -0,0 +1,297 @@ +use codeint_lang_sql::schema::{SqlSchema, collect_schema_hazards, schema_hazard_rules}; +use codeint_lang_sql::{ParsedSqlStatement, Sql, SqlDialect}; +use codeint_model::{HazardLine, RepoPath}; + +fn parse(dialect: SqlDialect, source: &str) -> Vec { + let path = RepoPath::new("queries/test.sql").expect("valid path"); + Sql::with_dialect(dialect) + .lower_with_details(&path, source) + .expect("lower succeeds") + .parsed_statements +} + +fn assert_hits_dialect( + dialect: SqlDialect, + schema_sql: &str, + query_sql: &str, + expected: &[(u32, &str)], +) { + let ddl = parse(dialect, schema_sql); + let schema = SqlSchema::build([ddl.as_slice()]); + let stmts = parse(dialect, query_sql); + let actual = collect_schema_hazards(&stmts, &schema); + let expected_lines: Vec = expected + .iter() + .map(|&(line, rule)| HazardLine { + line, + rule: rule.to_owned(), + }) + .collect(); + assert_eq!(actual, expected_lines); +} + +fn assert_hits(schema_sql: &str, query_sql: &str, expected: &[(u32, &str)]) { + assert_hits_dialect(SqlDialect::Generic, schema_sql, query_sql, expected); +} + +fn base_schema() -> &'static str { + r#" + CREATE TABLE users ( + id INT PRIMARY KEY, + email VARCHAR(255) NOT NULL, + code TEXT NOT NULL, + age INT NOT NULL, + tenant_id INT NOT NULL, + created_at TIMESTAMP NOT NULL + ); + CREATE INDEX idx_users_tenant_created ON users (tenant_id, created_at); + + CREATE TABLE orders ( + id INT PRIMARY KEY, + user_id INT NOT NULL, + status TEXT NOT NULL, + amount NUMERIC(10, 2) NOT NULL + ); + CREATE INDEX idx_orders_status ON orders (status); + "# +} + +#[test] +fn lists_all_five_schema_hazard_rules() { + let rules: Vec<&str> = schema_hazard_rules().collect(); + assert_eq!( + rules, + vec![ + "filter-on-unindexed-column", + "join-on-unindexed-column", + "order-by-unindexed-column", + "text-compared-to-number", + "unknown-column", + ] + ); +} + +#[test] +fn unknown_column_matches_missing_column_and_respects_valid_columns() { + assert_hits( + base_schema(), + "SELECT id,\n nonexistent_col\nFROM users\nWHERE id = 1;", + &[(2, "unknown-column")], + ); + assert_hits( + base_schema(), + "SELECT id, email FROM users WHERE id = 1;", + &[], + ); +} + +#[test] +fn unknown_column_matches_insert_update_and_delete_targets() { + assert_hits( + base_schema(), + "INSERT INTO users (id, ghost_col) VALUES (1, 'x');\nUPDATE users SET missing_field = 'y' WHERE id = 1;\nDELETE FROM users WHERE bogus = 1;", + &[ + (1, "unknown-column"), + (2, "unknown-column"), + (3, "unknown-column"), + ], + ); +} + +#[test] +fn text_compared_to_number_matches_bare_numbers_and_ignores_strings() { + assert_hits( + base_schema(), + "SELECT id\nFROM orders\nWHERE status = 42\n AND 7 < status\n AND status <> -1;", + &[ + (3, "text-compared-to-number"), + (4, "text-compared-to-number"), + (5, "text-compared-to-number"), + ], + ); + assert_hits( + base_schema(), + "SELECT id FROM orders WHERE status = '42' AND id = 42;", + &[], + ); +} + +#[test] +fn filter_on_unindexed_column_matches_unindexed_and_second_composite_column() { + assert_hits( + base_schema(), + "SELECT id\nFROM users\nWHERE email = 'a@b.com';", + &[(3, "filter-on-unindexed-column")], + ); + assert_hits( + base_schema(), + "SELECT id\nFROM users\nWHERE created_at > '2026-01-01';", + &[(3, "filter-on-unindexed-column")], + ); + assert_hits( + base_schema(), + "SELECT id FROM users WHERE id = 1 AND tenant_id = 5;", + &[], + ); +} + +#[test] +fn order_by_unindexed_column_matches_unindexed_and_stays_silent_on_aliases() { + assert_hits( + base_schema(), + "SELECT id\nFROM users\nWHERE id = 1\nORDER BY email DESC;", + &[(4, "order-by-unindexed-column")], + ); + assert_hits( + base_schema(), + "SELECT id\nFROM users\nORDER BY created_at;", + &[(3, "order-by-unindexed-column")], + ); + assert_hits( + base_schema(), + "SELECT id, age + 1 AS next_age FROM users ORDER BY id;\nSELECT id, age + 1 AS next_age FROM users ORDER BY tenant_id;\nSELECT id, age + 1 AS next_age FROM users ORDER BY next_age;\nSELECT id FROM users ORDER BY 1;", + &[], + ); +} + +#[test] +fn join_on_unindexed_column_matches_on_and_using_and_respects_pk_and_first_index() { + assert_hits( + base_schema(), + "SELECT u.id, o.id\nFROM users u\nJOIN orders o\n ON o.user_id = u.id;", + &[ + (4, "filter-on-unindexed-column"), + (4, "join-on-unindexed-column"), + ], + ); + assert_hits( + "CREATE TABLE users (id INT PRIMARY KEY);\nCREATE TABLE orders (id INT PRIMARY KEY, user_id INT NOT NULL);\nCREATE INDEX idx_orders_user ON orders (user_id);", + "SELECT u.id, o.id FROM users u JOIN orders o ON o.user_id = u.id;", + &[], + ); + assert_hits( + "CREATE TABLE a (id INT PRIMARY KEY, shared_key INT NOT NULL);\nCREATE TABLE b (id INT PRIMARY KEY, shared_key INT NOT NULL);", + "SELECT a.id\nFROM a\nJOIN b USING (shared_key);", + &[(3, "join-on-unindexed-column")], + ); +} + +#[test] +fn stays_silent_on_unknown_tables_ctes_and_derived_subqueries() { + assert_hits( + base_schema(), + "SELECT bogus FROM mystery_table WHERE fake = 123 ORDER BY whatever;", + &[], + ); + assert_hits( + base_schema(), + "WITH users AS (SELECT 1 AS custom_col)\nSELECT custom_col FROM users WHERE custom_col = 1 ORDER BY custom_col;", + &[], + ); + assert_hits( + base_schema(), + "SELECT sub.derived_col\nFROM (SELECT id AS derived_col FROM users WHERE id = 1) sub\nWHERE sub.derived_col = 1\nORDER BY sub.derived_col;", + &[], + ); +} + +#[test] +fn stays_silent_on_ambiguous_or_mixed_known_unknown_unqualified_columns() { + assert_hits( + "CREATE TABLE a (id INT PRIMARY KEY, status TEXT NOT NULL);\nCREATE TABLE b (id INT PRIMARY KEY, status TEXT NOT NULL);", + "SELECT id FROM a JOIN b ON a.id = b.id WHERE status = 1 ORDER BY status;", + &[], + ); + assert_hits( + base_schema(), + "SELECT id\nFROM users\nJOIN external_audit ON users.id = external_audit.user_id\nWHERE email = 'a@b.com'\n AND unknown_maybe_audit = 1\nORDER BY email;", + &[], + ); + assert_hits( + base_schema(), + "SELECT users.id\nFROM users\nJOIN external_audit ON users.id = external_audit.user_id\nWHERE users.email = 'a@b.com';", + &[(4, "filter-on-unindexed-column")], + ); +} + +#[test] +fn follows_migration_order_for_schema_backed_hazards() { + let m1 = parse( + SqlDialect::Postgresql, + "CREATE TABLE users (id INT PRIMARY KEY, handle TEXT NOT NULL);", + ); + let m2 = parse( + SqlDialect::Postgresql, + "CREATE INDEX idx_users_handle ON users (handle);", + ); + let m3 = parse( + SqlDialect::Postgresql, + "DROP INDEX idx_users_handle;\nALTER TABLE users DROP COLUMN handle;", + ); + let query = parse( + SqlDialect::Postgresql, + "SELECT id FROM users WHERE handle = 'ada';", + ); + + let s1 = SqlSchema::build([m1.as_slice()]); + assert_eq!( + collect_schema_hazards(&query, &s1), + vec![HazardLine { + line: 1, + rule: "filter-on-unindexed-column".to_owned(), + }] + ); + + let s2 = SqlSchema::build([m1.as_slice(), m2.as_slice()]); + assert!(collect_schema_hazards(&query, &s2).is_empty()); + + let s3 = SqlSchema::build([m1.as_slice(), m2.as_slice(), m3.as_slice()]); + assert_eq!( + collect_schema_hazards(&query, &s3), + vec![HazardLine { + line: 1, + rule: "unknown-column".to_owned(), + }] + ); +} + +#[test] +fn deduplicates_and_sorts_findings_by_line_and_rule() { + assert_hits( + base_schema(), + "SELECT u.id\nFROM users u\nWHERE u.code = 10 OR u.code = 20\nORDER BY u.email;", + &[ + (3, "filter-on-unindexed-column"), + (3, "text-compared-to-number"), + (4, "order-by-unindexed-column"), + ], + ); +} + +#[test] +fn correlated_subquery_resolves_outer_column_without_false_unknown() { + assert_hits( + "CREATE TABLE users (id INT PRIMARY KEY, name TEXT);\nCREATE TABLE orders (order_id INT PRIMARY KEY, user_id INT NOT NULL);\nCREATE INDEX idx_orders_user ON orders (user_id);", + "SELECT name FROM users WHERE EXISTS (SELECT 1 FROM orders WHERE user_id = id);", + &[], + ); +} + +#[test] +fn handles_sqlite_and_duckdb_dialects() { + assert_hits_dialect( + SqlDialect::Sqlite, + "CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT);", + "SELECT rowid, id FROM notes WHERE body = 99;", + &[ + (1, "filter-on-unindexed-column"), + (1, "text-compared-to-number"), + ], + ); + assert_hits_dialect( + SqlDialect::Duckdb, + "CREATE TABLE metrics (id INT PRIMARY KEY, tag VARCHAR);", + "SELECT id FROM metrics ORDER BY tag;", + &[(1, "order-by-unindexed-column")], + ); +} From cf434fc2f680cb88708b21d2de21167af89ce7c6 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Tue, 24 Nov 2026 21:24:17 +0800 Subject: [PATCH 05/12] feat(plugins): add 27 statement-level SQL Hazard line rules --- plugins/languages/sql/src/hazards.rs | 525 ++++++++++++++ plugins/languages/sql/src/hazards/dml_ddl.rs | 121 ++++ .../languages/sql/src/hazards/expr_util.rs | 316 ++++++++ plugins/languages/sql/src/hazards/joins.rs | 308 ++++++++ plugins/languages/sql/src/hazards/locate.rs | 140 ++++ .../languages/sql/src/hazards/predicates.rs | 251 +++++++ .../languages/sql/src/hazards/query_shape.rs | 310 ++++++++ plugins/languages/sql/src/hazards/secrets.rs | 230 ++++++ .../languages/sql/src/hazards/subqueries.rs | 235 ++++++ plugins/languages/sql/src/lib.rs | 12 +- plugins/languages/sql/tests/conformance.rs | 4 +- plugins/languages/sql/tests/hazards.rs | 676 ++++++++++++++++++ 12 files changed, 3123 insertions(+), 5 deletions(-) create mode 100644 plugins/languages/sql/src/hazards.rs create mode 100644 plugins/languages/sql/src/hazards/dml_ddl.rs create mode 100644 plugins/languages/sql/src/hazards/expr_util.rs create mode 100644 plugins/languages/sql/src/hazards/joins.rs create mode 100644 plugins/languages/sql/src/hazards/locate.rs create mode 100644 plugins/languages/sql/src/hazards/predicates.rs create mode 100644 plugins/languages/sql/src/hazards/query_shape.rs create mode 100644 plugins/languages/sql/src/hazards/secrets.rs create mode 100644 plugins/languages/sql/src/hazards/subqueries.rs create mode 100644 plugins/languages/sql/tests/hazards.rs diff --git a/plugins/languages/sql/src/hazards.rs b/plugins/languages/sql/src/hazards.rs new file mode 100644 index 00000000..f7d95983 --- /dev/null +++ b/plugins/languages/sql/src/hazards.rs @@ -0,0 +1,525 @@ +mod dml_ddl; +mod expr_util; +mod joins; +mod locate; +mod predicates; +mod query_shape; +mod secrets; +mod subqueries; + +use std::collections::{BTreeMap, BTreeSet}; + +use codeint_model::HazardLine; +use sqlparser::ast::{ + Delete, Expr, FromTable, FunctionArguments, InTarget, JoinConstraint, JoinOperator, + MacroDefinition, Merge, OnConflictAction, OnInsert, OrderByKind, Query, Select, SelectItem, + SetExpr, Statement, TableFactor, TableWithJoins, Update, UpdateTableFromKind, +}; +use sqlparser::tokenizer::TokenWithSpan; + +use crate::{ParsedSqlStatement, SqlDialect}; + +pub const SQL_HAZARD_RULES: &[&str] = &[ + "select-star", + "leading-wildcard-like", + "large-offset", + "tables-without-join-condition", + "distinct-with-order-by", + "subquery-in-select-list", + "function-on-filter-column", + "not-in-subquery", + "union-without-all", + "select-without-filter-or-limit", + "count-without-filter", + "order-by-random", + "distinct-over-join", + "table-read-twice", + "subquery-refers-to-outer-table", + "long-in-list", + "deep-subquery-nesting", + "join-without-aliases", + "column-position", + "update-without-filter", + "delete-without-filter", + "truncate", + "drop", + "grant-or-revoke", + "always-true-condition", + "sql-built-at-run-time", + "plain-text-secret", + "unknown-column", + "text-compared-to-number", + "filter-on-unindexed-column", + "order-by-unindexed-column", + "join-on-unindexed-column", +]; + +pub(crate) fn collect_statement_hazards( + parsed: &[ParsedSqlStatement], + dialect: SqlDialect, +) -> Vec { + let mut hits = BTreeSet::new(); + for stmt in parsed { + let mut ctx = HazardCtx { + tokens: &stmt.tokens, + stmt_start_line: stmt.start_line, + stmt_end_line: stmt.end_line, + _dialect: dialect, + hits: &mut hits, + }; + let mut walker = StatementWalker::new(&mut ctx); + walker.visit_statement(&stmt.statement); + walker.finish(); + } + hits.into_iter() + .map(|(line, rule)| HazardLine { + line, + rule: rule.to_owned(), + }) + .collect() +} + +pub fn hazard_line_rules() -> impl Iterator { + SQL_HAZARD_RULES.iter().copied() +} + +struct HazardCtx<'a> { + tokens: &'a [TokenWithSpan], + stmt_start_line: u32, + stmt_end_line: u32, + _dialect: SqlDialect, + hits: &'a mut BTreeSet<(u32, &'static str)>, +} + +impl HazardCtx<'_> { + fn emit(&mut self, line: u32, rule: &'static str) { + let max_line = self.stmt_end_line.max(self.stmt_start_line).max(1); + let resolved = if line >= 1 && line <= max_line { + line + } else { + self.stmt_start_line.clamp(1, max_line) + }; + self.hits.insert((resolved, rule)); + } +} + +struct StatementWalker<'a, 'b> { + ctx: &'a mut HazardCtx<'b>, + in_create_view: bool, + in_exists_direct: bool, + has_row_limit: bool, + subquery_depth: u32, + outer_scopes: Vec>, + cte_scopes: Vec>, + table_reads: BTreeMap, Vec>, +} + +impl<'a, 'b> StatementWalker<'a, 'b> { + fn new(ctx: &'a mut HazardCtx<'b>) -> Self { + Self { + ctx, + in_create_view: false, + in_exists_direct: false, + has_row_limit: false, + subquery_depth: 0, + outer_scopes: Vec::new(), + cte_scopes: Vec::new(), + table_reads: BTreeMap::new(), + } + } + + fn finish(self) { + joins::emit_table_read_twice(self.ctx, &self.table_reads); + } + + fn visit_statement(&mut self, stmt: &Statement) { + dml_ddl::check_statement(self.ctx, stmt); + secrets::check_statement(self.ctx, stmt); + match stmt { + Statement::Query(query) => self.visit_query(query), + Statement::Explain { statement, .. } | Statement::Prepare { statement, .. } => { + self.visit_statement(statement); + } + Statement::Insert(insert) => self.visit_insert(insert), + Statement::Update(update) => self.visit_update(update), + Statement::Delete(delete) => self.visit_delete(delete), + Statement::Merge(merge) => self.visit_merge(merge), + _ => self.visit_ddl_statement(stmt), + } + } + + fn visit_ddl_statement(&mut self, stmt: &Statement) { + match stmt { + Statement::CreateView(view) => { + let prev = self.in_create_view; + self.in_create_view = true; + self.visit_query(&view.query); + self.in_create_view = prev; + } + Statement::CreateTable(table) => { + if let Some(q) = table.query.as_deref() { + self.visit_query(q); + } + } + Statement::CreateIndex(index) => { + if let Some(pred) = &index.predicate { + self.visit_filter(pred, false); + } + } + Statement::CreateMacro { definition, .. } => match definition { + MacroDefinition::Expr(e) => self.visit_expr(e), + MacroDefinition::Table(q) => self.visit_query(q), + }, + _ => {} + } + } + + fn visit_insert(&mut self, insert: &sqlparser::ast::Insert) { + if let Some(src) = insert.source.as_deref() { + self.visit_query(src); + } + for assign in &insert.assignments { + self.visit_expr(&assign.value); + } + if let Some(OnInsert::OnConflict(conflict)) = &insert.on + && let OnConflictAction::DoUpdate(do_update) = &conflict.action + { + for assign in &do_update.assignments { + self.visit_expr(&assign.value); + } + if let Some(sel) = &do_update.selection { + self.visit_filter(sel, false); + } + } + } + + fn visit_update(&mut self, update: &Update) { + let mut scope = BTreeSet::new(); + self.visit_table_with_joins(&update.table); + subqueries::collect_twj_bindings(&update.table, &mut scope); + if let Some(from_kind) = &update.from { + let from_tables = match from_kind { + UpdateTableFromKind::BeforeSet(t) | UpdateTableFromKind::AfterSet(t) => t, + }; + for twj in from_tables { + self.visit_table_with_joins(twj); + subqueries::collect_twj_bindings(twj, &mut scope); + } + } + self.outer_scopes.push(scope); + for assign in &update.assignments { + self.visit_expr(&assign.value); + } + if let Some(sel) = &update.selection { + self.visit_filter(sel, false); + } + query_shape::check_order_by_exprs(self.ctx, &update.order_by); + self.outer_scopes.pop(); + } + + fn visit_delete(&mut self, delete: &Delete) { + let mut scope = BTreeSet::new(); + let from_tables = match &delete.from { + FromTable::WithFromKeyword(t) | FromTable::WithoutKeyword(t) => t, + }; + for twj in from_tables { + self.visit_table_with_joins(twj); + subqueries::collect_twj_bindings(twj, &mut scope); + } + if let Some(using) = &delete.using { + for twj in using { + self.visit_table_with_joins(twj); + subqueries::collect_twj_bindings(twj, &mut scope); + } + } + self.outer_scopes.push(scope); + if let Some(sel) = &delete.selection { + self.visit_filter(sel, false); + } + query_shape::check_order_by_exprs(self.ctx, &delete.order_by); + self.outer_scopes.pop(); + } + + fn visit_merge(&mut self, merge: &Merge) { + self.visit_filter(&merge.on, false); + for clause in &merge.clauses { + if let Some(pred) = &clause.predicate { + self.visit_filter(pred, false); + } + } + } + + fn visit_query(&mut self, query: &Query) { + let pushed_cte = self.visit_with_clause(query); + if let Some(limit) = &query.limit_clause { + query_shape::check_large_offset(self.ctx, limit); + } + query_shape::check_distinct_with_order_by(self.ctx, query); + if let Some(order_by) = &query.order_by + && let OrderByKind::Expressions(exprs) = &order_by.kind + { + query_shape::check_order_by_exprs(self.ctx, exprs); + } + + let prev_limit = self.has_row_limit; + self.has_row_limit = query_shape::query_has_row_limit(query); + self.visit_set_expr(&query.body); + self.has_row_limit = prev_limit; + + if let Some(order_by) = &query.order_by + && let OrderByKind::Expressions(exprs) = &order_by.kind + { + for item in exprs { + self.visit_expr(&item.expr); + } + } + if pushed_cte { + self.cte_scopes.pop(); + } + } + + fn visit_with_clause(&mut self, query: &Query) -> bool { + let Some(with) = &query.with else { + return false; + }; + let mut scope = BTreeSet::new(); + if with.recursive { + for cte in &with.cte_tables { + scope.insert(expr_util::normalize_ident(&cte.alias.name)); + } + } + self.cte_scopes.push(scope); + let prev_exists = self.in_exists_direct; + let prev_limit = self.has_row_limit; + self.in_exists_direct = false; + self.has_row_limit = false; + for cte in &with.cte_tables { + self.visit_query(&cte.query); + if let Some(top) = self.cte_scopes.last_mut() { + top.insert(expr_util::normalize_ident(&cte.alias.name)); + } + } + self.in_exists_direct = prev_exists; + self.has_row_limit = prev_limit; + true + } + + fn visit_set_expr(&mut self, set_expr: &SetExpr) { + match set_expr { + SetExpr::Select(select) => self.visit_select(select), + SetExpr::Query(inner) => self.visit_query(inner), + SetExpr::SetOperation { + left, + op, + set_quantifier, + right, + } => { + query_shape::check_union_without_all(self.ctx, *op, *set_quantifier, left, right); + self.visit_set_expr(left); + self.visit_set_expr(right); + } + SetExpr::Values(values) => { + for row in &values.rows { + for expr in row.iter() { + self.visit_expr(expr); + } + } + } + SetExpr::Insert(s) | SetExpr::Update(s) | SetExpr::Delete(s) | SetExpr::Merge(s) => { + self.visit_statement(s); + } + SetExpr::Table(_) => {} + } + } + + fn visit_select(&mut self, select: &Select) { + if !self.in_exists_direct { + query_shape::check_select_star(self.ctx, select); + } + if !self.in_create_view && !self.has_row_limit { + query_shape::check_select_without_filter_or_limit(self.ctx, select); + } + query_shape::check_count_without_filter(self.ctx, select); + query_shape::check_subquery_in_select_list(self.ctx, select); + query_shape::check_group_by_column_position(self.ctx, &select.group_by); + query_shape::check_order_by_exprs(self.ctx, &select.sort_by); + joins::check_tables_without_join_condition(self.ctx, select); + joins::check_distinct_over_join(self.ctx, select); + joins::check_join_without_aliases(self.ctx, select); + + let saved_exists = self.in_exists_direct; + self.in_exists_direct = false; + + let mut from_scope = BTreeSet::new(); + for twj in &select.from { + self.visit_twj_with_lateral_scope(twj, &mut from_scope); + } + + let local_bindings = subqueries::collect_select_bindings(select); + self.outer_scopes.push(local_bindings); + self.visit_select_clauses(select); + self.outer_scopes.pop(); + self.in_exists_direct = saved_exists; + } + + fn visit_twj_with_lateral_scope( + &mut self, + twj: &TableWithJoins, + sibling_scope: &mut BTreeSet, + ) { + self.visit_table_factor_with_siblings(&twj.relation, sibling_scope); + subqueries::collect_factor_bindings(&twj.relation, sibling_scope); + for join in &twj.joins { + self.visit_table_factor_with_siblings(&join.relation, sibling_scope); + subqueries::collect_factor_bindings(&join.relation, sibling_scope); + self.visit_join_operator(&join.join_operator); + } + } + + fn visit_table_factor_with_siblings( + &mut self, + factor: &TableFactor, + sibling_scope: &mut BTreeSet, + ) { + joins::record_table_factor_read(factor, &self.cte_scopes, &mut self.table_reads); + match factor { + TableFactor::Derived { + lateral, subquery, .. + } => { + if *lateral && !sibling_scope.is_empty() { + self.outer_scopes.push(sibling_scope.clone()); + self.visit_subquery(subquery, false, true); + self.outer_scopes.pop(); + } else { + self.visit_subquery(subquery, false, false); + } + } + TableFactor::NestedJoin { + table_with_joins, .. + } => { + self.visit_twj_with_lateral_scope(table_with_joins, sibling_scope); + } + _ => {} + } + } + + fn visit_select_clauses(&mut self, select: &Select) { + for item in &select.projection { + self.visit_select_item(item); + } + if let Some(prewhere) = &select.prewhere { + self.visit_filter(prewhere, false); + } + if let Some(selection) = &select.selection { + self.visit_filter(selection, false); + } + if let Some(having) = &select.having { + self.visit_filter(having, true); + } + if let Some(qualify) = &select.qualify { + self.visit_filter(qualify, false); + } + } + + fn visit_select_item(&mut self, item: &SelectItem) { + if let Some(expr) = expr_util::select_item_expr(item) { + self.visit_expr(expr); + } + } + + fn visit_table_with_joins(&mut self, twj: &TableWithJoins) { + let mut empty = BTreeSet::new(); + self.visit_twj_with_lateral_scope(twj, &mut empty); + } + + fn visit_join_operator(&mut self, op: &JoinOperator) { + if let JoinOperator::AsOf { + match_condition, .. + } = op + { + self.visit_filter(match_condition, false); + } + if let Some(JoinConstraint::On(expr)) = expr_util::join_constraint(op) { + self.visit_filter(expr, false); + } + } + + fn visit_filter(&mut self, expr: &Expr, in_having: bool) { + predicates::check_filter_expr(self.ctx, expr, in_having); + self.visit_expr(expr); + } + + fn visit_subquery(&mut self, subquery: &Query, is_exists: bool, check_correlation: bool) { + if check_correlation { + subqueries::check_correlated_subquery(self.ctx, subquery, &self.outer_scopes); + } + self.subquery_depth += 1; + if self.subquery_depth >= 3 { + subqueries::emit_deep_nesting(self.ctx, subquery); + } + let prev_exists = self.in_exists_direct; + let prev_limit = self.has_row_limit; + self.in_exists_direct = is_exists; + self.has_row_limit = false; + self.visit_query(subquery); + self.in_exists_direct = prev_exists; + self.has_row_limit = prev_limit; + self.subquery_depth -= 1; + } + + fn visit_expr(&mut self, expr: &Expr) { + match expr { + Expr::Like { .. } | Expr::ILike { .. } => { + predicates::check_leading_wildcard_like(self.ctx, expr); + self.visit_expr_children(expr); + } + Expr::In { + expr: lhs, target, .. + } => { + predicates::check_in_expr(self.ctx, expr); + self.visit_expr(lhs); + self.visit_in_target(target); + } + Expr::Subquery(q) => self.visit_subquery(q, false, true), + Expr::Exists { subquery, .. } => self.visit_subquery(subquery, true, true), + Expr::Function(func) => self.visit_function(func), + _ => self.visit_expr_children(expr), + } + } + + fn visit_in_target(&mut self, target: &InTarget) { + match target { + InTarget::Subquery(q) => self.visit_subquery(q, false, true), + InTarget::List(items) => { + for item in items { + self.visit_expr(item); + } + } + InTarget::Unnest(e) => self.visit_expr(e), + InTarget::Table { .. } => {} + } + } + + fn visit_function(&mut self, func: &sqlparser::ast::Function) { + if let Some(filter) = &func.filter { + self.visit_filter(filter, false); + } + match &func.args { + FunctionArguments::Subquery(q) => self.visit_subquery(q, false, true), + FunctionArguments::List(list) => { + for arg in &list.args { + if let Some(e) = expr_util::function_arg_expr(arg) { + self.visit_expr(e); + } + } + } + FunctionArguments::None => {} + } + } + + fn visit_expr_children(&mut self, expr: &Expr) { + expr_util::for_each_child_expr(expr, &mut |child| { + self.visit_expr(child); + }); + } +} diff --git a/plugins/languages/sql/src/hazards/dml_ddl.rs b/plugins/languages/sql/src/hazards/dml_ddl.rs new file mode 100644 index 00000000..a85a2157 --- /dev/null +++ b/plugins/languages/sql/src/hazards/dml_ddl.rs @@ -0,0 +1,121 @@ +use sqlparser::ast::{Delete, Expr, ObjectName, Statement, Update}; +use sqlparser::keywords::Keyword; + +use super::HazardCtx; +use super::expr_util::last_ident_lower; +use super::locate::first_keyword_line; + +pub(super) fn check_statement(ctx: &mut HazardCtx<'_>, stmt: &Statement) { + match stmt { + Statement::Update(update) => check_update(ctx, update), + Statement::Delete(delete) => check_delete(ctx, delete), + Statement::Truncate(_) => { + let line = first_keyword_line(ctx.tokens, Keyword::TRUNCATE); + ctx.emit(line, "truncate"); + } + Statement::Grant(_) | Statement::GrantRole(_) => { + let line = first_keyword_line(ctx.tokens, Keyword::GRANT); + ctx.emit(line, "grant-or-revoke"); + } + Statement::Revoke(_) | Statement::RevokeRole(_) => { + let line = first_keyword_line(ctx.tokens, Keyword::REVOKE); + ctx.emit(line, "grant-or-revoke"); + } + Statement::Execute { + name, + parameters, + immediate, + .. + } => check_execute(ctx, name.as_ref(), parameters, *immediate), + _ if is_drop_statement(stmt) => { + let line = first_keyword_line(ctx.tokens, Keyword::DROP); + ctx.emit(line, "drop"); + } + _ => {} + } +} + +fn check_update(ctx: &mut HazardCtx<'_>, update: &Update) { + if update.selection.is_some() { + return; + } + let tok_line = update.update_token.0.span.start.line as u32; + let line = if tok_line > 0 { + tok_line + } else { + first_keyword_line(ctx.tokens, Keyword::UPDATE) + }; + ctx.emit(line, "update-without-filter"); +} + +fn check_delete(ctx: &mut HazardCtx<'_>, delete: &Delete) { + if delete.selection.is_some() { + return; + } + let tok_line = delete.delete_token.0.span.start.line as u32; + let line = if tok_line > 0 { + tok_line + } else { + first_keyword_line(ctx.tokens, Keyword::DELETE) + }; + ctx.emit(line, "delete-without-filter"); +} + +fn is_drop_statement(stmt: &Statement) -> bool { + matches!( + stmt, + Statement::Drop { .. } + | Statement::DropFunction(_) + | Statement::DropDomain(_) + | Statement::DropProcedure { .. } + | Statement::DropSecret { .. } + | Statement::DropPolicy(_) + | Statement::DropRule(_) + | Statement::DropConnector { .. } + | Statement::DropExtension(_) + | Statement::DropOperator(_) + | Statement::DropOperatorFamily(_) + | Statement::DropOperatorClass(_) + | Statement::DropTrigger(_) + ) +} + +fn check_execute( + ctx: &mut HazardCtx<'_>, + name: Option<&ObjectName>, + parameters: &[Expr], + immediate: bool, +) { + if is_dynamic_execute(name, parameters, immediate) { + let line = first_keyword_line(ctx.tokens, Keyword::EXECUTE); + let fallback = if line > 0 { + line + } else { + first_keyword_line(ctx.tokens, Keyword::EXEC) + }; + ctx.emit(fallback, "sql-built-at-run-time"); + } +} + +fn is_dynamic_execute(name: Option<&ObjectName>, parameters: &[Expr], immediate: bool) -> bool { + if immediate { + return true; + } + let Some(obj) = name else { + return !parameters.is_empty(); + }; + if obj.0.len() == 1 + && obj.0[0] + .as_ident() + .is_some_and(|id| id.quote_style == Some('\'')) + { + return true; + } + if parameters.is_empty() { + return false; + } + let Some(last) = last_ident_lower(obj) else { + return false; + }; + matches!(last.as_str(), "immediate" | "sp_executesql" | "format") +} diff --git a/plugins/languages/sql/src/hazards/expr_util.rs b/plugins/languages/sql/src/hazards/expr_util.rs new file mode 100644 index 00000000..2ace013a --- /dev/null +++ b/plugins/languages/sql/src/hazards/expr_util.rs @@ -0,0 +1,316 @@ +use sqlparser::ast::{ + CaseWhen, Expr, Function, FunctionArg, FunctionArgExpr, FunctionArguments, Ident, InTarget, + JoinConstraint, JoinOperator, ObjectName, SelectItem, UnaryOperator, Value, +}; + +pub(super) fn peel_nested(mut expr: &Expr) -> &Expr { + while let Expr::Nested(inner) = expr { + expr = inner; + } + expr +} + +pub(super) fn normalize_ident(ident: &Ident) -> String { + if ident.quote_style.is_none() { + ident.value.to_ascii_lowercase() + } else { + ident.value.clone() + } +} + +pub(super) fn object_name_key(name: &ObjectName) -> Option> { + let mut parts = Vec::with_capacity(name.0.len()); + for part in &name.0 { + let ident = part.as_ident()?; + parts.push(normalize_ident(ident)); + } + if parts.is_empty() { None } else { Some(parts) } +} + +pub(super) fn last_ident_lower(name: &ObjectName) -> Option { + name.0 + .last() + .and_then(|part| part.as_ident()) + .map(|ident| ident.value.to_ascii_lowercase()) +} + +pub(super) fn select_item_expr(item: &SelectItem) -> Option<&Expr> { + match item { + SelectItem::UnnamedExpr(e) + | SelectItem::ExprWithAlias { expr: e, .. } + | SelectItem::ExprWithAliases { expr: e, .. } => Some(e), + SelectItem::Wildcard(_) | SelectItem::QualifiedWildcard(_, _) => None, + } +} + +pub(super) fn join_constraint(op: &JoinOperator) -> Option<&JoinConstraint> { + use JoinOperator::{ + Anti, AsOf, CrossJoin, FullOuter, Inner, Join, Left, LeftAnti, LeftOuter, LeftSemi, Right, + RightAnti, RightOuter, RightSemi, Semi, StraightJoin, + }; + match op { + Join(c) | Inner(c) | Left(c) | LeftOuter(c) | Right(c) | RightOuter(c) | FullOuter(c) + | CrossJoin(c) | Semi(c) | LeftSemi(c) | RightSemi(c) | Anti(c) | LeftAnti(c) + | RightAnti(c) | StraightJoin(c) => Some(c), + AsOf { constraint, .. } => Some(constraint), + _ => None, + } +} + +pub(super) fn extract_string_literal(expr: &Expr) -> Option<&str> { + let Expr::Value(val) = peel_nested(expr) else { + return None; + }; + value_as_str(&val.value) +} + +pub(super) fn value_as_str(value: &Value) -> Option<&str> { + match value { + Value::SingleQuotedString(s) + | Value::DoubleQuotedString(s) + | Value::TripleSingleQuotedString(s) + | Value::TripleDoubleQuotedString(s) + | Value::EscapedStringLiteral(s) + | Value::UnicodeStringLiteral(s) + | Value::SingleQuotedByteStringLiteral(s) + | Value::DoubleQuotedByteStringLiteral(s) + | Value::TripleSingleQuotedByteStringLiteral(s) + | Value::TripleDoubleQuotedByteStringLiteral(s) + | Value::SingleQuotedRawStringLiteral(s) + | Value::DoubleQuotedRawStringLiteral(s) + | Value::TripleSingleQuotedRawStringLiteral(s) + | Value::TripleDoubleQuotedRawStringLiteral(s) + | Value::NationalStringLiteral(s) + | Value::HexStringLiteral(s) => Some(s.as_str()), + Value::DollarQuotedString(s) => Some(s.value.as_str()), + Value::QuoteDelimitedStringLiteral(s) | Value::NationalQuoteDelimitedStringLiteral(s) => { + Some(s.value.as_str()) + } + _ => None, + } +} + +pub(super) fn is_string_literal_value(value: &Value) -> bool { + value_as_str(value).is_some() +} + +pub(super) fn is_string_literal_expr(expr: &Expr) -> bool { + matches!(peel_nested(expr), Expr::Value(v) if is_string_literal_value(&v.value)) +} + +pub(super) fn extract_uint_literal(expr: &Expr) -> Option { + match peel_nested(expr) { + Expr::Value(val) => parse_uint_value(&val.value), + Expr::UnaryOp { + op: UnaryOperator::Plus, + expr: inner, + } => extract_uint_literal(inner), + _ => None, + } +} + +fn parse_uint_value(value: &Value) -> Option { + let Value::Number(raw, _) = value else { + return None; + }; + if raw.is_empty() || !raw.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + raw.parse::().ok() +} + +pub(super) fn function_arg_expr(arg: &FunctionArg) -> Option<&Expr> { + match arg { + FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) + | FunctionArg::Named { + arg: FunctionArgExpr::Expr(e), + .. + } + | FunctionArg::ExprNamed { + arg: FunctionArgExpr::Expr(e), + .. + } => Some(e), + _ => None, + } +} + +pub(super) fn expr_contains_column(expr: &Expr) -> bool { + match expr { + Expr::Identifier(_) | Expr::CompoundIdentifier(_) => true, + Expr::Subquery(_) | Expr::Exists { .. } => false, + other => { + let mut found = false; + for_each_child_expr(other, &mut |child| { + if !found && expr_contains_column(child) { + found = true; + } + }); + found + } + } +} + +pub(super) fn function_args_any(func: &Function, pred: fn(&Expr) -> bool) -> bool { + let FunctionArguments::List(list) = &func.args else { + return false; + }; + list.args.iter().filter_map(function_arg_expr).any(pred) +} + +pub(super) fn for_each_child_expr<'a>(expr: &'a Expr, visit: &mut impl FnMut(&'a Expr)) { + if let Some(child) = unary_or_test_child(expr) { + visit(child); + return; + } + if let Some((a, b)) = binary_or_match_children(expr) { + visit(a); + visit(b); + return; + } + visit_structured_expr_children(expr, visit); +} + +fn unary_or_test_child(expr: &Expr) -> Option<&Expr> { + match expr { + Expr::Nested(e) | Expr::UnaryOp { expr: e, .. } | Expr::Collate { expr: e, .. } => Some(e), + Expr::Cast { expr: e, .. } + | Expr::Convert { expr: e, .. } + | Expr::Extract { expr: e, .. } + | Expr::Ceil { expr: e, .. } + | Expr::Floor { expr: e, .. } + | Expr::Trim { expr: e, .. } => Some(e), + other => predicate_test_child(other), + } +} + +fn predicate_test_child(expr: &Expr) -> Option<&Expr> { + use Expr::{ + IsFalse, IsNotFalse, IsNotNull, IsNotTrue, IsNotUnknown, IsNull, IsTrue, IsUnknown, + }; + match expr { + IsNull(e) | IsNotNull(e) | IsTrue(e) | IsNotTrue(e) | IsFalse(e) | IsNotFalse(e) + | IsUnknown(e) | IsNotUnknown(e) => Some(e), + _ => None, + } +} + +fn binary_or_match_children(expr: &Expr) -> Option<(&Expr, &Expr)> { + match expr { + Expr::BinaryOp { left, right, .. } => Some((left, right)), + Expr::Like { + expr: lhs, + pattern: rhs, + .. + } + | Expr::ILike { + expr: lhs, + pattern: rhs, + .. + } + | Expr::Position { + expr: lhs, + r#in: rhs, + } => Some((lhs, rhs)), + Expr::IsDistinctFrom(a, b) + | Expr::IsNotDistinctFrom(a, b) + | Expr::AnyOp { + left: a, right: b, .. + } + | Expr::AllOp { + left: a, right: b, .. + } => Some((a, b)), + _ => None, + } +} + +fn visit_structured_expr_children<'a>(expr: &'a Expr, visit: &mut impl FnMut(&'a Expr)) { + match expr { + Expr::Function(func) => visit_function_children(func, visit), + Expr::Between { + expr: target, + low, + high, + .. + } => { + visit(target); + visit(low); + visit(high); + } + Expr::Case { + operand, + conditions, + else_result, + .. + } => visit_case_children( + operand.as_deref(), + conditions, + else_result.as_deref(), + visit, + ), + Expr::In { + expr: lhs, target, .. + } => visit_in_children(lhs, target, visit), + Expr::Tuple(items) => items.iter().for_each(visit), + Expr::Substring { + expr: target, + substring_from, + substring_for, + .. + } => { + visit(target); + substring_from.as_deref().into_iter().for_each(&mut *visit); + substring_for.as_deref().into_iter().for_each(visit); + } + Expr::Overlay { + expr: target, + overlay_what, + overlay_from, + overlay_for, + } => { + visit(target); + visit(overlay_what); + visit(overlay_from); + overlay_for.as_deref().into_iter().for_each(visit); + } + _ => {} + } +} + +fn visit_function_children<'a>(func: &'a Function, visit: &mut impl FnMut(&'a Expr)) { + if let FunctionArguments::List(list) = &func.args { + list.args + .iter() + .filter_map(function_arg_expr) + .for_each(&mut *visit); + } + if let Some(filter) = &func.filter { + visit(filter); + } +} + +fn visit_case_children<'a>( + operand: Option<&'a Expr>, + conditions: &'a [CaseWhen], + else_result: Option<&'a Expr>, + visit: &mut impl FnMut(&'a Expr), +) { + if let Some(op) = operand { + visit(op); + } + for when in conditions { + visit(&when.condition); + visit(&when.result); + } + if let Some(els) = else_result { + visit(els); + } +} + +fn visit_in_children<'a>(lhs: &'a Expr, target: &'a InTarget, visit: &mut impl FnMut(&'a Expr)) { + visit(lhs); + match target { + InTarget::List(items) => items.iter().for_each(visit), + InTarget::Unnest(inner) => visit(inner), + InTarget::Subquery(_) | InTarget::Table { .. } => {} + } +} diff --git a/plugins/languages/sql/src/hazards/joins.rs b/plugins/languages/sql/src/hazards/joins.rs new file mode 100644 index 00000000..6e5e57e7 --- /dev/null +++ b/plugins/languages/sql/src/hazards/joins.rs @@ -0,0 +1,308 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use sqlparser::ast::{ + BinaryOperator, Distinct, Expr, Join, JoinConstraint, JoinOperator, Select, Spanned, + TableFactor, TableWithJoins, +}; +use sqlparser::keywords::Keyword; + +use super::HazardCtx; +use super::expr_util::{ + for_each_child_expr, join_constraint, normalize_ident, object_name_key, peel_nested, +}; +use super::locate::{ + first_keyword_line, keyword_line_at_or_after, keyword_pair_line_before, select_line, + select_start_loc, span_line, +}; + +pub(super) fn check_tables_without_join_condition(ctx: &mut HazardCtx<'_>, select: &Select) { + let where_links = select.selection.as_ref().is_some_and(expr_links_tables); + let from_start = select + .from + .first() + .map_or_else(|| select_start_loc(select), |t| t.span().start); + + if select.from.len() >= 2 && !where_links { + let from_line = + keyword_line_at_or_after(ctx.tokens, Keyword::FROM, select_start_loc(select)); + let line = if from_line > 0 { + from_line + } else { + span_line(select.from[0].span()) + }; + ctx.emit(line, "tables-without-join-condition"); + } + + for twj in &select.from { + check_joins_for_missing_condition(ctx, twj, where_links, from_start); + } +} + +fn check_joins_for_missing_condition( + ctx: &mut HazardCtx<'_>, + twj: &TableWithJoins, + where_links: bool, + from_start: sqlparser::tokenizer::Location, +) { + if let TableFactor::NestedJoin { + table_with_joins, .. + } = &twj.relation + { + check_joins_for_missing_condition(ctx, table_with_joins, where_links, from_start); + } + for join in &twj.joins { + if let TableFactor::NestedJoin { + table_with_joins, .. + } = &join.relation + { + check_joins_for_missing_condition(ctx, table_with_joins, where_links, from_start); + } + check_single_join_condition(ctx, join, where_links, from_start); + } +} + +fn check_single_join_condition( + ctx: &mut HazardCtx<'_>, + join: &Join, + where_links: bool, + from_start: sqlparser::tokenizer::Location, +) { + let rel_loc = join.relation.span().start; + if matches!(join.join_operator, JoinOperator::CrossJoin(_)) { + let cross = keyword_pair_line_before(ctx.tokens, Keyword::CROSS, Keyword::JOIN, rel_loc); + let line = if cross > 0 { + cross + } else { + span_line(join.relation.span()) + }; + ctx.emit(line, "tables-without-join-condition"); + return; + } + if join_has_no_constraint(&join.join_operator) && !where_links { + let join_kw = keyword_line_at_or_after(ctx.tokens, Keyword::JOIN, from_start); + let line = if join_kw > 0 { + join_kw + } else { + span_line(join.relation.span()) + }; + ctx.emit(line, "tables-without-join-condition"); + } +} + +fn join_has_no_constraint(op: &JoinOperator) -> bool { + !matches!(op, JoinOperator::CrossJoin(_) | JoinOperator::AsOf { .. }) + && matches!(join_constraint(op), Some(JoinConstraint::None)) +} + +fn expr_links_tables(expr: &Expr) -> bool { + match peel_nested(expr) { + Expr::BinaryOp { left, op, right } => binary_expr_links_tables(left, op, right), + Expr::IsDistinctFrom(left, right) | Expr::IsNotDistinctFrom(left, right) => { + sides_link_tables(left, right) + } + Expr::UnaryOp { expr: inner, .. } => expr_links_tables(inner), + _ => false, + } +} + +fn binary_expr_links_tables(left: &Expr, op: &BinaryOperator, right: &Expr) -> bool { + if matches!(op, BinaryOperator::And | BinaryOperator::Or) { + return expr_links_tables(left) || expr_links_tables(right); + } + if matches!( + op, + BinaryOperator::Eq + | BinaryOperator::NotEq + | BinaryOperator::Lt + | BinaryOperator::LtEq + | BinaryOperator::Gt + | BinaryOperator::GtEq + | BinaryOperator::Spaceship + ) { + return sides_link_tables(left, right); + } + false +} + +fn sides_link_tables(left: &Expr, right: &Expr) -> bool { + let mut left_quals = BTreeSet::new(); + let mut right_quals = BTreeSet::new(); + let left_has_col = collect_column_qualifiers(left, &mut left_quals); + let right_has_col = collect_column_qualifiers(right, &mut right_quals); + if !left_has_col || !right_has_col { + return false; + } + if left_quals.len() == 1 && left_quals == right_quals { + return false; + } + true +} + +fn collect_column_qualifiers(expr: &Expr, quals: &mut BTreeSet) -> bool { + match peel_nested(expr) { + Expr::Identifier(_) => true, + Expr::CompoundIdentifier(idents) if idents.len() >= 2 => { + quals.insert(normalize_ident(&idents[0])); + true + } + Expr::Subquery(_) | Expr::Exists { .. } => false, + other => { + let mut found = false; + for_each_child_expr(other, &mut |child| { + if collect_column_qualifiers(child, quals) { + found = true; + } + }); + found + } + } +} + +pub(super) fn check_distinct_over_join(ctx: &mut HazardCtx<'_>, select: &Select) { + if !matches!(select.distinct, Some(Distinct::Distinct | Distinct::On(_))) { + return; + } + let table_count = count_from_tables(&select.from); + if table_count < 2 { + return; + } + let kw = keyword_line_at_or_after(ctx.tokens, Keyword::DISTINCT, select_start_loc(select)); + let line = if kw > 0 { + kw + } else { + select_line(select, ctx.tokens) + }; + ctx.emit(line, "distinct-over-join"); +} + +pub(super) fn check_join_without_aliases(ctx: &mut HazardCtx<'_>, select: &Select) { + let mut total = 0usize; + let mut missing_alias = false; + let mut has_explicit_join = false; + + for twj in &select.from { + if !twj.joins.is_empty() { + has_explicit_join = true; + } + inspect_twj_aliases(twj, &mut total, &mut missing_alias); + } + + if total < 2 || !missing_alias { + return; + } + let start = select_start_loc(select); + let kw = if has_explicit_join { + keyword_line_at_or_after(ctx.tokens, Keyword::JOIN, start) + } else { + keyword_line_at_or_after(ctx.tokens, Keyword::FROM, start) + }; + let line = if kw > 0 { + kw + } else { + span_line(select.from[0].span()) + }; + ctx.emit(line, "join-without-aliases"); +} + +fn inspect_twj_aliases(twj: &TableWithJoins, total: &mut usize, missing_alias: &mut bool) { + inspect_factor_alias(&twj.relation, total, missing_alias); + for join in &twj.joins { + inspect_factor_alias(&join.relation, total, missing_alias); + } +} + +fn inspect_factor_alias(factor: &TableFactor, total: &mut usize, missing_alias: &mut bool) { + if let TableFactor::NestedJoin { + table_with_joins, .. + } = factor + { + inspect_twj_aliases(table_with_joins, total, missing_alias); + return; + } + *total += 1; + if !table_factor_has_alias(factor) { + *missing_alias = true; + } +} + +fn table_factor_has_alias(factor: &TableFactor) -> bool { + match factor { + TableFactor::Table { alias, .. } + | TableFactor::Derived { alias, .. } + | TableFactor::TableFunction { alias, .. } + | TableFactor::Function { alias, .. } + | TableFactor::UNNEST { alias, .. } + | TableFactor::JsonTable { alias, .. } + | TableFactor::OpenJsonTable { alias, .. } + | TableFactor::NestedJoin { alias, .. } + | TableFactor::Pivot { alias, .. } + | TableFactor::Unpivot { alias, .. } + | TableFactor::MatchRecognize { alias, .. } => alias.is_some(), + _ => true, + } +} + +fn count_from_tables(from: &[TableWithJoins]) -> usize { + from.iter().map(count_twj_tables).sum() +} + +fn count_twj_tables(twj: &TableWithJoins) -> usize { + let base = count_factor_tables(&twj.relation); + let joined: usize = twj + .joins + .iter() + .map(|j| count_factor_tables(&j.relation)) + .sum(); + base + joined +} + +fn count_factor_tables(factor: &TableFactor) -> usize { + match factor { + TableFactor::NestedJoin { + table_with_joins, .. + } => count_twj_tables(table_with_joins), + _ => 1, + } +} + +pub(super) fn record_table_factor_read( + factor: &TableFactor, + cte_scopes: &[BTreeSet], + reads: &mut BTreeMap, Vec>, +) { + let TableFactor::Table { + name, args: None, .. + } = factor + else { + return; + }; + let Some(key) = object_name_key(name) else { + return; + }; + if key.len() == 1 && is_cte_in_scope(&key[0], cte_scopes) { + return; + } + let line = span_line(name.span()); + reads.entry(key).or_default().push(line); +} + +fn is_cte_in_scope(name: &str, cte_scopes: &[BTreeSet]) -> bool { + cte_scopes.iter().any(|scope| scope.contains(name)) +} + +pub(super) fn emit_table_read_twice( + ctx: &mut HazardCtx<'_>, + reads: &BTreeMap, Vec>, +) { + for lines in reads.values() { + if lines.len() > 1 { + let line = lines[1]; + let resolved = if line > 0 { + line + } else { + first_keyword_line(ctx.tokens, Keyword::FROM) + }; + ctx.emit(resolved, "table-read-twice"); + } + } +} diff --git a/plugins/languages/sql/src/hazards/locate.rs b/plugins/languages/sql/src/hazards/locate.rs new file mode 100644 index 00000000..8e6c31a9 --- /dev/null +++ b/plugins/languages/sql/src/hazards/locate.rs @@ -0,0 +1,140 @@ +use sqlparser::ast::{Select, Spanned}; +use sqlparser::keywords::Keyword; +use sqlparser::tokenizer::{Location, Span, Token, TokenWithSpan}; + +pub(super) fn span_line(span: Span) -> u32 { + span.start.line as u32 +} + +pub(super) fn is_keyword(tok: &TokenWithSpan, kw: Keyword) -> bool { + matches!(&tok.token, Token::Word(w) if w.quote_style.is_none() && w.keyword == kw) +} + +pub(super) fn is_code_token(tok: &TokenWithSpan) -> bool { + !matches!(tok.token, Token::Whitespace(_) | Token::EOF) +} + +pub(super) fn first_keyword_line(tokens: &[TokenWithSpan], kw: Keyword) -> u32 { + tokens + .iter() + .find(|t| is_keyword(t, kw)) + .map_or(0, |t| t.span.start.line as u32) +} + +pub(super) fn keyword_line_at_or_after( + tokens: &[TokenWithSpan], + kw: Keyword, + min_loc: Location, +) -> u32 { + if min_loc.line == 0 { + return first_keyword_line(tokens, kw); + } + tokens + .iter() + .find(|t| t.span.start >= min_loc && is_keyword(t, kw)) + .map_or(0, |t| t.span.start.line as u32) +} + +pub(super) fn keyword_line_in_range( + tokens: &[TokenWithSpan], + kw: Keyword, + start: Location, + end: Location, +) -> u32 { + if start.line == 0 || end.line == 0 { + return first_keyword_line(tokens, kw); + } + tokens + .iter() + .find(|t| t.span.start >= start && t.span.end <= end && is_keyword(t, kw)) + .map_or(0, |t| t.span.start.line as u32) +} + +pub(super) fn keyword_line_before( + tokens: &[TokenWithSpan], + kw: Keyword, + before_loc: Location, +) -> u32 { + if before_loc.line == 0 { + return first_keyword_line(tokens, kw); + } + let Some(idx) = tokens + .iter() + .rposition(|t| t.span.start < before_loc && is_code_token(t)) + else { + return 0; + }; + for tok in tokens[..=idx].iter().rev() { + if !is_code_token(tok) { + continue; + } + if is_keyword(tok, kw) { + return tok.span.start.line as u32; + } + if !matches!(tok.token, Token::LParen | Token::Word(_)) { + break; + } + } + 0 +} + +pub(super) fn keyword_pair_line_before( + tokens: &[TokenWithSpan], + first: Keyword, + second: Keyword, + before_loc: Location, +) -> u32 { + if before_loc.line == 0 { + return first_keyword_pair_line(tokens, first, second); + } + let code: Vec<&TokenWithSpan> = tokens + .iter() + .filter(|t| t.span.start < before_loc && is_code_token(t)) + .collect(); + for pair in code.windows(2).rev() { + if is_keyword(pair[0], first) && is_keyword(pair[1], second) { + return pair[0].span.start.line as u32; + } + } + 0 +} + +pub(super) fn first_keyword_pair_line( + tokens: &[TokenWithSpan], + first: Keyword, + second: Keyword, +) -> u32 { + let mut prev_matches = false; + let mut prev_line = 0u32; + for tok in tokens { + if !is_code_token(tok) { + continue; + } + if prev_matches && is_keyword(tok, second) { + return prev_line; + } + prev_matches = is_keyword(tok, first); + prev_line = tok.span.start.line as u32; + } + 0 +} + +pub(super) fn select_line(select: &Select, tokens: &[TokenWithSpan]) -> u32 { + let tok_line = select.select_token.0.span.start.line as u32; + if tok_line > 0 { + return tok_line; + } + let span_l = span_line(select.span()); + if span_l > 0 { + return span_l; + } + first_keyword_line(tokens, Keyword::SELECT) +} + +pub(super) fn select_start_loc(select: &Select) -> Location { + if select.select_token.0.span.start.line > 0 { + select.select_token.0.span.start + } else { + select.span().start + } +} diff --git a/plugins/languages/sql/src/hazards/predicates.rs b/plugins/languages/sql/src/hazards/predicates.rs new file mode 100644 index 00000000..64269714 --- /dev/null +++ b/plugins/languages/sql/src/hazards/predicates.rs @@ -0,0 +1,251 @@ +use sqlparser::ast::{ + BinaryOperator, DuplicateTreatment, Expr, Function, FunctionArguments, InTarget, Spanned, + UnaryOperator, Value, +}; +use sqlparser::keywords::Keyword; + +use super::HazardCtx; +use super::expr_util::{ + expr_contains_column, extract_string_literal, for_each_child_expr, function_args_any, + last_ident_lower, peel_nested, value_as_str, +}; +use super::locate::{keyword_line_before, span_line}; + +const HAVING_AGGREGATES: &[&str] = &[ + "any_value", + "array_agg", + "avg", + "bit_and", + "bit_or", + "bit_xor", + "bool_and", + "bool_or", + "count", + "every", + "first", + "group_concat", + "json_agg", + "json_arrayagg", + "json_object_agg", + "jsonb_agg", + "jsonb_object_agg", + "last", + "list", + "max", + "median", + "min", + "percentile_cont", + "percentile_disc", + "stddev", + "stddev_pop", + "stddev_samp", + "string_agg", + "sum", + "total", + "var_pop", + "var_samp", + "variance", +]; + +pub(super) fn check_leading_wildcard_like(ctx: &mut HazardCtx<'_>, expr: &Expr) { + let (pattern, kw) = match expr { + Expr::Like { pattern, .. } => (pattern.as_ref(), Keyword::LIKE), + Expr::ILike { pattern, .. } => (pattern.as_ref(), Keyword::ILIKE), + _ => return, + }; + let Some(lit) = extract_string_literal(pattern) else { + return; + }; + if !lit.starts_with('%') && !lit.starts_with('_') { + return; + } + let kw_line = keyword_line_before(ctx.tokens, kw, pattern.span().start); + let line = if kw_line > 0 { + kw_line + } else { + span_line(expr.span()) + }; + ctx.emit(line, "leading-wildcard-like"); +} + +pub(super) fn check_in_expr(ctx: &mut HazardCtx<'_>, expr: &Expr) { + let Expr::In { + target, negated, .. + } = expr + else { + return; + }; + match target { + InTarget::Subquery(subquery) if *negated => { + let not_line = keyword_line_before(ctx.tokens, Keyword::NOT, subquery.span().start); + let line = if not_line > 0 { + not_line + } else { + span_line(expr.span()) + }; + ctx.emit(line, "not-in-subquery"); + } + InTarget::List(items) if items.len() > 100 => { + let first_loc = items[0].span().start; + let in_line = keyword_line_before(ctx.tokens, Keyword::IN, first_loc); + let line = if in_line > 0 { + in_line + } else { + span_line(expr.span()) + }; + ctx.emit(line, "long-in-list"); + } + _ => {} + } +} + +pub(super) fn check_filter_expr(ctx: &mut HazardCtx<'_>, expr: &Expr, in_having: bool) { + check_always_true(ctx, expr, true); + check_function_on_column(ctx, expr, in_having); +} + +fn check_always_true(ctx: &mut HazardCtx<'_>, expr: &Expr, in_bool_pos: bool) { + let unwrapped = peel_nested(expr); + if in_bool_pos && is_always_true_literal(unwrapped) { + ctx.emit(span_line(unwrapped.span()), "always-true-condition"); + return; + } + match unwrapped { + Expr::BinaryOp { left, op, right } => { + check_always_true_binary(ctx, unwrapped, left, op, right); + } + Expr::IsNotDistinctFrom(left, right) if same_constant(left, right) => { + ctx.emit(span_line(unwrapped.span()), "always-true-condition"); + } + _ => {} + } +} + +fn check_always_true_binary( + ctx: &mut HazardCtx<'_>, + whole: &Expr, + left: &Expr, + op: &BinaryOperator, + right: &Expr, +) { + if matches!( + op, + BinaryOperator::And | BinaryOperator::Or | BinaryOperator::Xor + ) { + check_always_true(ctx, left, true); + check_always_true(ctx, right, true); + return; + } + if matches!( + op, + BinaryOperator::Eq + | BinaryOperator::GtEq + | BinaryOperator::LtEq + | BinaryOperator::Spaceship + ) && same_constant(left, right) + { + ctx.emit(span_line(whole.span()), "always-true-condition"); + } +} + +fn is_always_true_literal(expr: &Expr) -> bool { + match expr { + Expr::Value(val) => val.value == Value::Boolean(true), + Expr::UnaryOp { + op: UnaryOperator::Not, + expr: inner, + } => matches!(peel_nested(inner), Expr::Value(val) if val.value == Value::Boolean(false)), + _ => false, + } +} + +#[derive(PartialEq, Eq)] +enum ConstVal { + Num(String), + Str(String), + Bool(bool), +} + +fn same_constant(left: &Expr, right: &Expr) -> bool { + match (extract_const(left), extract_const(right)) { + (Some(a), Some(b)) => a == b, + _ => false, + } +} + +fn extract_const(expr: &Expr) -> Option { + match peel_nested(expr) { + Expr::Value(val) => value_to_const(&val.value), + Expr::UnaryOp { + op: UnaryOperator::Plus, + expr: inner, + } => extract_const(inner), + Expr::UnaryOp { + op: UnaryOperator::Minus, + expr: inner, + } => match extract_const(inner)? { + ConstVal::Num(n) => Some(ConstVal::Num(format!("-{n}"))), + _ => None, + }, + _ => None, + } +} + +fn value_to_const(value: &Value) -> Option { + if let Some(s) = value_as_str(value) { + return Some(ConstVal::Str(s.to_owned())); + } + match value { + Value::Number(raw, _) => Some(ConstVal::Num(raw.clone())), + Value::Boolean(b) => Some(ConstVal::Bool(*b)), + _ => None, + } +} + +fn check_function_on_column(ctx: &mut HazardCtx<'_>, expr: &Expr, in_having: bool) { + match expr { + Expr::Subquery(_) | Expr::Exists { .. } => {} + Expr::Function(func) => check_function_call(ctx, expr, func, in_having), + Expr::Substring { .. } + | Expr::Trim { .. } + | Expr::Extract { .. } + | Expr::Ceil { .. } + | Expr::Floor { .. } + | Expr::Position { .. } + | Expr::Overlay { .. } => { + if expr_contains_column(expr) { + ctx.emit(span_line(expr.span()), "function-on-filter-column"); + } + } + other => for_each_child_expr(other, &mut |child| { + check_function_on_column(ctx, child, in_having); + }), + } +} + +fn check_function_call(ctx: &mut HazardCtx<'_>, expr: &Expr, func: &Function, in_having: bool) { + if in_having && is_having_aggregate(func) { + return; + } + if function_args_any(func, expr_contains_column) { + let line = span_line(expr.span()); + ctx.emit(line, "function-on-filter-column"); + } +} + +fn is_having_aggregate(func: &Function) -> bool { + func.over.is_none() && (has_aggregate_modifier(func) || is_aggregate_name(func)) +} + +fn has_aggregate_modifier(func: &Function) -> bool { + let is_distinct = matches!( + &func.args, + FunctionArguments::List(list) if list.duplicate_treatment == Some(DuplicateTreatment::Distinct) + ); + func.filter.is_some() || !func.within_group.is_empty() || is_distinct +} + +fn is_aggregate_name(func: &Function) -> bool { + last_ident_lower(&func.name) + .is_some_and(|name| HAVING_AGGREGATES.binary_search(&name.as_str()).is_ok()) +} diff --git a/plugins/languages/sql/src/hazards/query_shape.rs b/plugins/languages/sql/src/hazards/query_shape.rs new file mode 100644 index 00000000..a4c8f1a7 --- /dev/null +++ b/plugins/languages/sql/src/hazards/query_shape.rs @@ -0,0 +1,310 @@ +use sqlparser::ast::{ + Distinct, Expr, Function, FunctionArg, FunctionArgExpr, FunctionArguments, GroupByExpr, + InTarget, LimitClause, OrderBy, OrderByExpr, OrderByKind, Query, Select, SelectItem, SetExpr, + SetOperator, SetQuantifier, Spanned, +}; +use sqlparser::keywords::Keyword; + +use super::HazardCtx; +use super::expr_util::{ + extract_uint_literal, for_each_child_expr, function_arg_expr, last_ident_lower, peel_nested, + select_item_expr, +}; +use super::locate::{ + first_keyword_line, keyword_line_at_or_after, keyword_line_before, keyword_line_in_range, + keyword_pair_line_before, select_line, select_start_loc, span_line, +}; + +const RANDOM_FUNCTIONS: &[&str] = &["gen_random_uuid", "newid", "rand", "random"]; + +pub(super) fn query_has_row_limit(query: &Query) -> bool { + if query.fetch.is_some() { + return true; + } + match &query.limit_clause { + Some(LimitClause::LimitOffset { limit, .. }) => limit.is_some(), + Some(LimitClause::OffsetCommaLimit { .. }) => true, + None => false, + } +} + +pub(super) fn check_select_star(ctx: &mut HazardCtx<'_>, select: &Select) { + for item in &select.projection { + if matches!( + item, + SelectItem::Wildcard(_) | SelectItem::QualifiedWildcard(_, _) + ) { + let item_line = span_line(item.span()); + let line = if item_line > 0 { + item_line + } else { + select_line(select, ctx.tokens) + }; + ctx.emit(line, "select-star"); + } + } +} + +pub(super) fn check_large_offset(ctx: &mut HazardCtx<'_>, limit: &LimitClause) { + match limit { + LimitClause::LimitOffset { + offset: Some(offset), + .. + } if extract_uint_literal(&offset.value).is_some_and(|n| n > 1000) => { + let kw = keyword_line_before(ctx.tokens, Keyword::OFFSET, offset.value.span().start); + let line = if kw > 0 { + kw + } else { + span_line(offset.value.span()) + }; + ctx.emit(line, "large-offset"); + } + LimitClause::OffsetCommaLimit { offset, .. } + if extract_uint_literal(offset).is_some_and(|n| n > 1000) => + { + let line = span_line(offset.span()); + let resolved = if line > 0 { + line + } else { + first_keyword_line(ctx.tokens, Keyword::LIMIT) + }; + ctx.emit(resolved, "large-offset"); + } + _ => {} + } +} + +pub(super) fn check_distinct_with_order_by(ctx: &mut HazardCtx<'_>, query: &Query) { + if !has_non_empty_order_by(query.order_by.as_ref()) { + return; + } + let Some(select) = direct_distinct_select(&query.body) else { + return; + }; + let kw = keyword_line_at_or_after(ctx.tokens, Keyword::DISTINCT, select_start_loc(select)); + let line = if kw > 0 { + kw + } else { + select_line(select, ctx.tokens) + }; + ctx.emit(line, "distinct-with-order-by"); +} + +fn has_non_empty_order_by(order_by: Option<&OrderBy>) -> bool { + match order_by.map(|o| &o.kind) { + Some(OrderByKind::All(_)) => true, + Some(OrderByKind::Expressions(exprs)) => !exprs.is_empty(), + None => false, + } +} + +fn direct_distinct_select(body: &SetExpr) -> Option<&Select> { + match body { + SetExpr::Select(select) if matches!(select.distinct, Some(Distinct::Distinct)) => { + Some(select) + } + SetExpr::Query(inner) if inner.order_by.is_none() => direct_distinct_select(&inner.body), + _ => None, + } +} + +pub(super) fn check_subquery_in_select_list(ctx: &mut HazardCtx<'_>, select: &Select) { + for item in &select.projection { + if let Some(expr) = select_item_expr(item) { + emit_subqueries_in_expr(ctx, expr, span_line(item.span())); + } + } +} + +fn emit_subqueries_in_expr(ctx: &mut HazardCtx<'_>, expr: &Expr, fallback_line: u32) { + match expr { + Expr::Subquery(q) | Expr::Exists { subquery: q, .. } => { + let line = query_first_line(ctx, q, fallback_line); + ctx.emit(line, "subquery-in-select-list"); + } + Expr::In { + expr: lhs, + target: InTarget::Subquery(q), + .. + } => { + emit_subqueries_in_expr(ctx, lhs, fallback_line); + let line = query_first_line(ctx, q, fallback_line); + ctx.emit(line, "subquery-in-select-list"); + } + _ => for_each_child_expr(expr, &mut |child| { + emit_subqueries_in_expr(ctx, child, fallback_line); + }), + } +} + +pub(super) fn query_first_line(ctx: &HazardCtx<'_>, query: &Query, fallback: u32) -> u32 { + if let SetExpr::Select(sel) = query.body.as_ref() { + let line = select_line(sel, ctx.tokens); + if line > 0 { + return line; + } + } + let span_l = span_line(query.span()); + if span_l > 0 { span_l } else { fallback } +} + +pub(super) fn check_union_without_all( + ctx: &mut HazardCtx<'_>, + op: SetOperator, + quantifier: SetQuantifier, + left: &SetExpr, + right: &SetExpr, +) { + if op != SetOperator::Union { + return; + } + if matches!(quantifier, SetQuantifier::All | SetQuantifier::AllByName) { + return; + } + let line = keyword_line_in_range( + ctx.tokens, + Keyword::UNION, + left.span().end, + right.span().start, + ); + ctx.emit(line, "union-without-all"); +} + +pub(super) fn check_select_without_filter_or_limit(ctx: &mut HazardCtx<'_>, select: &Select) { + if select.from.is_empty() + || select.selection.is_some() + || select.prewhere.is_some() + || select.top.is_some() + { + return; + } + let line = select_line(select, ctx.tokens); + ctx.emit(line, "select-without-filter-or-limit"); +} + +pub(super) fn check_count_without_filter(ctx: &mut HazardCtx<'_>, select: &Select) { + if select.from.is_empty() || select.selection.is_some() || select.prewhere.is_some() { + return; + } + let sel_line = select_line(select, ctx.tokens); + for expr in select.projection.iter().filter_map(select_item_expr) { + emit_count_star_in_expr(ctx, expr, sel_line); + } +} + +fn emit_count_star_in_expr(ctx: &mut HazardCtx<'_>, expr: &Expr, fallback: u32) { + if matches!(expr, Expr::Subquery(_) | Expr::Exists { .. }) { + return; + } + if let Expr::Function(func) = expr + && is_unfiltered_count_star(func) + { + let line = span_line(expr.span()); + ctx.emit( + if line > 0 { line } else { fallback }, + "count-without-filter", + ); + return; + } + for_each_child_expr(expr, &mut |child| { + emit_count_star_in_expr(ctx, child, fallback); + }); +} + +fn is_unfiltered_count_star(func: &Function) -> bool { + if func.filter.is_some() { + return false; + } + if last_ident_lower(&func.name).as_deref() != Some("count") { + return false; + } + let FunctionArguments::List(list) = &func.args else { + return false; + }; + matches!( + list.args.as_slice(), + [FunctionArg::Unnamed(FunctionArgExpr::Wildcard)] + ) +} + +pub(super) fn check_order_by_exprs(ctx: &mut HazardCtx<'_>, exprs: &[OrderByExpr]) { + let first_loc = exprs.first().map(|e| e.expr.span().start); + let clause_line = first_loc + .map(|loc| keyword_pair_line_before(ctx.tokens, Keyword::ORDER, Keyword::BY, loc)) + .unwrap_or(0); + for item in exprs { + if expr_contains_random_call(&item.expr) { + let expr_line = span_line(item.expr.span()); + let line = if clause_line > 0 { + clause_line + } else { + expr_line + }; + ctx.emit(line, "order-by-random"); + } + if extract_uint_literal(&item.expr).is_some() { + let expr_line = span_line(item.expr.span()); + let line = if expr_line > 0 { + expr_line + } else { + clause_line + }; + ctx.emit(line, "column-position"); + } + } +} + +pub(super) fn check_group_by_column_position(ctx: &mut HazardCtx<'_>, group_by: &GroupByExpr) { + let GroupByExpr::Expressions(exprs, _) = group_by else { + return; + }; + let first_loc = exprs.first().map(|e| e.span().start); + let clause_line = first_loc + .map(|loc| keyword_pair_line_before(ctx.tokens, Keyword::GROUP, Keyword::BY, loc)) + .unwrap_or(0); + for expr in exprs { + if extract_uint_literal(expr).is_some() { + let expr_line = span_line(expr.span()); + let line = if expr_line > 0 { + expr_line + } else { + clause_line + }; + ctx.emit(line, "column-position"); + } + } +} + +fn expr_contains_random_call(expr: &Expr) -> bool { + match peel_nested(expr) { + Expr::Subquery(_) | Expr::Exists { .. } => false, + Expr::Function(func) => { + if is_random_function(func) { + return true; + } + let FunctionArguments::List(list) = &func.args else { + return false; + }; + list.args + .iter() + .filter_map(function_arg_expr) + .any(expr_contains_random_call) + } + other => { + let mut found = false; + for_each_child_expr(other, &mut |child| { + if !found && expr_contains_random_call(child) { + found = true; + } + }); + found + } + } +} + +fn is_random_function(func: &Function) -> bool { + let Some(name) = last_ident_lower(&func.name) else { + return false; + }; + RANDOM_FUNCTIONS.binary_search(&name.as_str()).is_ok() +} diff --git a/plugins/languages/sql/src/hazards/secrets.rs b/plugins/languages/sql/src/hazards/secrets.rs new file mode 100644 index 00000000..dc28ee9e --- /dev/null +++ b/plugins/languages/sql/src/hazards/secrets.rs @@ -0,0 +1,230 @@ +use sqlparser::ast::helpers::key_value_options::{ + KeyValueOption, KeyValueOptionKind, KeyValueOptions, +}; +use sqlparser::ast::{ + AlterRoleOperation, AlterUser, Assignment, AssignmentTarget, CreateRole, CreateServerOption, + CreateUser, Expr, Insert, ObjectName, OnConflictAction, OnInsert, Password, RoleOption, + SecretOption, SetExpr, Spanned, Statement, +}; +use sqlparser::keywords::Keyword; + +use super::HazardCtx; +use super::expr_util::{ + is_string_literal_expr, is_string_literal_value, last_ident_lower, peel_nested, + select_item_expr, +}; +use super::locate::{first_keyword_line, span_line}; + +const SENSITIVE_SUBSTRINGS: &[&str] = &[ + "password", + "passwd", + "pwd", + "secret", + "token", + "api_key", + "apikey", + "private_key", + "access_key", +]; + +pub(super) fn is_sensitive_name(name: &str) -> bool { + let lower = name.to_ascii_lowercase(); + SENSITIVE_SUBSTRINGS.iter().any(|s| lower.contains(s)) +} + +pub(super) fn check_statement(ctx: &mut HazardCtx<'_>, stmt: &Statement) { + match stmt { + Statement::CreateRole(role) => check_create_role(ctx, role), + Statement::AlterRole { operation, .. } => check_alter_role(ctx, operation), + Statement::CreateUser(user) => check_create_user(ctx, user), + Statement::AlterUser(user) => check_alter_user(ctx, user), + Statement::CreateSecret { options, .. } => check_create_secret(ctx, options), + Statement::CreateUserMapping(mapping) => { + if let Some(opts) = &mapping.options { + check_server_options(ctx, opts); + } + } + Statement::Insert(insert) => check_insert(ctx, insert), + Statement::Update(update) => check_assignments(ctx, &update.assignments), + _ => {} + } +} + +fn check_create_role(ctx: &mut HazardCtx<'_>, role: &CreateRole) { + if let Some(password) = &role.password { + check_password(ctx, password); + } +} + +fn check_alter_role(ctx: &mut HazardCtx<'_>, operation: &AlterRoleOperation) { + if let AlterRoleOperation::WithOptions { options } = operation { + for opt in options { + if let RoleOption::Password(password) = opt { + check_password(ctx, password); + } + } + } +} + +fn check_password(ctx: &mut HazardCtx<'_>, password: &Password) { + if let Password::Password(expr) = password + && is_string_literal_expr(expr) + { + let line = password_line(ctx, expr); + ctx.emit(line, "plain-text-secret"); + } +} + +fn password_line(ctx: &HazardCtx<'_>, expr: &Expr) -> u32 { + let expr_line = span_line(expr.span()); + if expr_line > 0 { + expr_line + } else { + first_keyword_line(ctx.tokens, Keyword::PASSWORD) + } +} + +fn check_create_user(ctx: &mut HazardCtx<'_>, user: &CreateUser) { + check_key_value_options(ctx, &user.options); +} + +fn check_alter_user(ctx: &mut HazardCtx<'_>, user: &AlterUser) { + if let Some(pw) = &user.password + && pw.password.is_some() + { + let line = first_keyword_line(ctx.tokens, Keyword::PASSWORD); + ctx.emit(line, "plain-text-secret"); + } + check_key_value_options(ctx, &user.set_props); +} + +fn check_key_value_options(ctx: &mut HazardCtx<'_>, kv: &KeyValueOptions) { + for opt in &kv.options { + check_kv_option(ctx, opt); + } +} + +fn check_kv_option(ctx: &mut HazardCtx<'_>, opt: &KeyValueOption) { + if !is_sensitive_name(&opt.option_name) { + if let KeyValueOptionKind::KeyValueOptions(nested) = &opt.option_value { + check_key_value_options(ctx, nested); + } + return; + } + match &opt.option_value { + KeyValueOptionKind::Single(val) if is_string_literal_value(&val.value) => { + ctx.emit(span_line(val.span), "plain-text-secret"); + } + KeyValueOptionKind::Multi(vals) => { + for val in vals { + if is_string_literal_value(&val.value) { + ctx.emit(span_line(val.span), "plain-text-secret"); + } + } + } + KeyValueOptionKind::KeyValueOptions(nested) => check_key_value_options(ctx, nested), + _ => {} + } +} + +fn check_create_secret(ctx: &mut HazardCtx<'_>, options: &[SecretOption]) { + for opt in options { + if opt.value.quote_style == Some('\'') && is_sensitive_name(&opt.key.value) { + let line = span_line(opt.value.span); + let resolved = if line > 0 { + line + } else { + first_keyword_line(ctx.tokens, Keyword::SECRET) + }; + ctx.emit(resolved, "plain-text-secret"); + } + } +} + +fn check_server_options(ctx: &mut HazardCtx<'_>, options: &[CreateServerOption]) { + for opt in options { + if opt.value.quote_style == Some('\'') && is_sensitive_name(&opt.key.value) { + let line = span_line(opt.value.span); + ctx.emit(line, "plain-text-secret"); + } + } +} + +fn check_insert(ctx: &mut HazardCtx<'_>, insert: &Insert) { + check_assignments(ctx, &insert.assignments); + check_on_insert(ctx, insert.on.as_ref()); + if insert.columns.is_empty() { + return; + } + let Some(source) = insert.source.as_deref() else { + return; + }; + match source.body.as_ref() { + SetExpr::Values(values) => { + for row in &values.rows { + check_column_expr_pairs(ctx, &insert.columns, row.iter()); + } + } + SetExpr::Select(select) => { + let exprs = select.projection.iter().map(select_item_expr); + for (col, maybe_expr) in insert.columns.iter().zip(exprs) { + if let Some(expr) = maybe_expr { + check_column_value(ctx, col, expr); + } + } + } + _ => {} + } +} + +fn check_on_insert(ctx: &mut HazardCtx<'_>, on: Option<&OnInsert>) { + match on { + Some(OnInsert::DuplicateKeyUpdate(assignments)) => check_assignments(ctx, assignments), + Some(OnInsert::OnConflict(conflict)) => { + if let OnConflictAction::DoUpdate(do_update) = &conflict.action { + check_assignments(ctx, &do_update.assignments); + } + } + _ => {} + } +} + +fn check_column_expr_pairs<'a>( + ctx: &mut HazardCtx<'_>, + columns: &[ObjectName], + values: impl Iterator, +) { + for (col, expr) in columns.iter().zip(values) { + check_column_value(ctx, col, expr); + } +} + +fn check_assignments(ctx: &mut HazardCtx<'_>, assignments: &[Assignment]) { + for assign in assignments { + match &assign.target { + AssignmentTarget::ColumnName(col) => check_column_value(ctx, col, &assign.value), + AssignmentTarget::Tuple(cols) => { + if let Expr::Tuple(vals) = peel_nested(&assign.value) { + check_column_expr_pairs(ctx, cols, vals.iter()); + } + } + } + } +} + +fn check_column_value(ctx: &mut HazardCtx<'_>, col: &ObjectName, value: &Expr) { + if !is_sensitive_column(col) || !is_string_literal_expr(value) { + return; + } + let val_line = span_line(value.span()); + let line = if val_line > 0 { + val_line + } else { + span_line(col.span()) + }; + ctx.emit(line, "plain-text-secret"); +} + +fn is_sensitive_column(col: &ObjectName) -> bool { + last_ident_lower(col).is_some_and(|name| is_sensitive_name(&name)) +} diff --git a/plugins/languages/sql/src/hazards/subqueries.rs b/plugins/languages/sql/src/hazards/subqueries.rs new file mode 100644 index 00000000..b30bbf13 --- /dev/null +++ b/plugins/languages/sql/src/hazards/subqueries.rs @@ -0,0 +1,235 @@ +use std::collections::BTreeSet; + +use sqlparser::ast::{ + Expr, GroupByExpr, JoinConstraint, OrderByKind, Query, Select, SelectItem, SetExpr, + TableFactor, TableWithJoins, +}; + +use super::HazardCtx; +use super::expr_util::{ + for_each_child_expr, join_constraint, normalize_ident, object_name_key, select_item_expr, +}; +use super::query_shape::query_first_line; + +pub(super) fn collect_twj_bindings(twj: &TableWithJoins, out: &mut BTreeSet) { + collect_factor_bindings(&twj.relation, out); + for join in &twj.joins { + collect_factor_bindings(&join.relation, out); + } +} + +pub(super) fn collect_factor_bindings(factor: &TableFactor, out: &mut BTreeSet) { + match factor { + TableFactor::Table { name, alias, .. } => { + if let Some(a) = alias { + out.insert(normalize_ident(&a.name)); + } else if let Some(parts) = object_name_key(name) { + if let Some(last) = parts.last() { + out.insert(last.clone()); + } + if parts.len() >= 2 { + out.insert(parts.join(".")); + } + } + } + TableFactor::Derived { alias: Some(a), .. } + | TableFactor::TableFunction { alias: Some(a), .. } + | TableFactor::Function { alias: Some(a), .. } + | TableFactor::UNNEST { alias: Some(a), .. } + | TableFactor::JsonTable { alias: Some(a), .. } + | TableFactor::OpenJsonTable { alias: Some(a), .. } => { + out.insert(normalize_ident(&a.name)); + } + TableFactor::NestedJoin { + table_with_joins, + alias, + } => { + if let Some(a) = alias { + out.insert(normalize_ident(&a.name)); + } + collect_twj_bindings(table_with_joins, out); + } + _ => {} + } +} + +pub(super) fn collect_select_bindings(select: &Select) -> BTreeSet { + let mut bindings = BTreeSet::new(); + for twj in &select.from { + collect_twj_bindings(twj, &mut bindings); + } + bindings +} + +pub(super) fn check_correlated_subquery( + ctx: &mut HazardCtx<'_>, + subquery: &Query, + outer_scopes: &[BTreeSet], +) { + if outer_scopes.is_empty() { + return; + } + if query_refers_to_outer(subquery, outer_scopes) { + let line = query_first_line(ctx, subquery, ctx.stmt_start_line); + ctx.emit(line, "subquery-refers-to-outer-table"); + } +} + +pub(super) fn emit_deep_nesting(ctx: &mut HazardCtx<'_>, subquery: &Query) { + let line = query_first_line(ctx, subquery, ctx.stmt_start_line); + ctx.emit(line, "deep-subquery-nesting"); +} + +fn query_refers_to_outer(query: &Query, outer_scopes: &[BTreeSet]) -> bool { + if set_expr_refers_to_outer(&query.body, outer_scopes) { + return true; + } + let Some(order_by) = &query.order_by else { + return false; + }; + let OrderByKind::Expressions(exprs) = &order_by.kind else { + return false; + }; + let body_bindings = set_expr_bindings(&query.body); + exprs + .iter() + .any(|o| expr_refers_to_outer(&o.expr, &body_bindings, outer_scopes)) +} + +fn set_expr_bindings(body: &SetExpr) -> BTreeSet { + match body { + SetExpr::Select(sel) => collect_select_bindings(sel), + SetExpr::Query(q) => set_expr_bindings(&q.body), + _ => BTreeSet::new(), + } +} + +fn set_expr_refers_to_outer(body: &SetExpr, outer_scopes: &[BTreeSet]) -> bool { + match body { + SetExpr::Select(select) => select_refers_to_outer(select, outer_scopes), + SetExpr::Query(inner) => query_refers_to_outer(inner, outer_scopes), + SetExpr::SetOperation { left, right, .. } => { + set_expr_refers_to_outer(left, outer_scopes) + || set_expr_refers_to_outer(right, outer_scopes) + } + _ => false, + } +} + +fn select_refers_to_outer(select: &Select, outer_scopes: &[BTreeSet]) -> bool { + let local = collect_select_bindings(select); + if projection_refers_to_outer(&select.projection, &local, outer_scopes) { + return true; + } + if join_ons_refer_to_outer(&select.from, &local, outer_scopes) { + return true; + } + let opt_exprs = [ + select.prewhere.as_ref(), + select.selection.as_ref(), + select.having.as_ref(), + select.qualify.as_ref(), + ]; + if opt_exprs + .into_iter() + .flatten() + .any(|e| expr_refers_to_outer(e, &local, outer_scopes)) + { + return true; + } + if let GroupByExpr::Expressions(exprs, _) = &select.group_by + && exprs + .iter() + .any(|e| expr_refers_to_outer(e, &local, outer_scopes)) + { + return true; + } + false +} + +fn projection_refers_to_outer( + projection: &[SelectItem], + local: &BTreeSet, + outer_scopes: &[BTreeSet], +) -> bool { + for item in projection { + if let Some(e) = select_item_expr(item) { + if expr_refers_to_outer(e, local, outer_scopes) { + return true; + } + } else if let SelectItem::QualifiedWildcard(kind, _) = item { + let text = kind.to_string().to_ascii_lowercase(); + if !local.contains(&text) && in_outer_scopes(&text, outer_scopes) { + return true; + } + } + } + false +} + +fn join_ons_refer_to_outer( + from: &[TableWithJoins], + local: &BTreeSet, + outer_scopes: &[BTreeSet], +) -> bool { + for twj in from { + for join in &twj.joins { + if let Some(JoinConstraint::On(expr)) = join_constraint(&join.join_operator) + && expr_refers_to_outer(expr, local, outer_scopes) + { + return true; + } + } + } + false +} + +fn expr_refers_to_outer( + expr: &Expr, + local: &BTreeSet, + outer_scopes: &[BTreeSet], +) -> bool { + match expr { + Expr::Subquery(_) | Expr::Exists { .. } => false, + Expr::CompoundIdentifier(idents) if idents.len() >= 2 => { + compound_refers_to_outer(idents, local, outer_scopes) + } + other => { + let mut found = false; + for_each_child_expr(other, &mut |child| { + if !found && expr_refers_to_outer(child, local, outer_scopes) { + found = true; + } + }); + found + } + } +} + +fn compound_refers_to_outer( + idents: &[sqlparser::ast::Ident], + local: &BTreeSet, + outer_scopes: &[BTreeSet], +) -> bool { + if idents.len() >= 3 { + let two_part = format!( + "{}.{}", + normalize_ident(&idents[0]), + normalize_ident(&idents[1]) + ); + if local.contains(&two_part) { + return false; + } + if in_outer_scopes(&two_part, outer_scopes) { + return true; + } + let table_part = normalize_ident(&idents[1]); + return !local.contains(&table_part) && in_outer_scopes(&table_part, outer_scopes); + } + let qual = normalize_ident(&idents[0]); + !local.contains(&qual) && in_outer_scopes(&qual, outer_scopes) +} + +fn in_outer_scopes(name: &str, outer_scopes: &[BTreeSet]) -> bool { + outer_scopes.iter().any(|scope| scope.contains(name)) +} diff --git a/plugins/languages/sql/src/lib.rs b/plugins/languages/sql/src/lib.rs index 9a000aa6..f1eb0b16 100644 --- a/plugins/languages/sql/src/lib.rs +++ b/plugins/languages/sql/src/lib.rs @@ -1,6 +1,7 @@ #![forbid(unsafe_code)] mod flagged; +mod hazards; mod parser; mod source_set; mod statements; @@ -18,6 +19,7 @@ use codeint_model::{ }; pub use flagged::flagged_line_rules; +pub use hazards::{SQL_HAZARD_RULES, hazard_line_rules}; pub use parser::{ParsedSqlStatement, RejectedSqlStatement}; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -113,13 +115,14 @@ impl Sql { let (parsed_statements, rejected_statements) = parse_all_statements(path, self.dialect, extracted); let flagged_lines = flagged::evaluate(&parsed_statements, &code_lines); + let hazard_lines = hazards::collect_statement_hazards(&parsed_statements, self.dialect); let source_set = source_set::classify(path, source); Ok(SqlLowerOutput { file_model: FileModel { runtime_imports: Vec::new(), flagged_lines, - hazard_lines: Vec::new(), + hazard_lines, tokens: duplication_tokens, functions, source_lines, @@ -182,11 +185,14 @@ impl LanguagePlugin for Sql { } fn has_hazard_rules(&self) -> bool { - false + true } fn hazard_rules(&self) -> Vec { - Vec::new() + SQL_HAZARD_RULES + .iter() + .map(|rule| (*rule).to_owned()) + .collect() } fn has_imports(&self) -> bool { diff --git a/plugins/languages/sql/tests/conformance.rs b/plugins/languages/sql/tests/conformance.rs index 95863c7e..8d5bb04d 100644 --- a/plugins/languages/sql/tests/conformance.rs +++ b/plugins/languages/sql/tests/conformance.rs @@ -24,8 +24,8 @@ fn sql_plugin_shell_dialects_empty_comments_and_unparsable_files() { assert_eq!(sql.dialect(), SqlDialect::Generic); assert_eq!(sql.extensions(), ["sql"]); assert!(!sql.has_imports()); - assert!(!sql.has_hazard_rules()); - assert!(sql.hazard_rules().is_empty()); + assert!(sql.has_hazard_rules()); + assert_eq!(sql.hazard_rules().len(), 32); assert!( sql.reference_ranges() .unwrap() diff --git a/plugins/languages/sql/tests/hazards.rs b/plugins/languages/sql/tests/hazards.rs new file mode 100644 index 00000000..012a9822 --- /dev/null +++ b/plugins/languages/sql/tests/hazards.rs @@ -0,0 +1,676 @@ +use std::collections::BTreeSet; + +use codeint_lang_sql::{SQL_HAZARD_RULES, Sql, SqlDialect, hazard_line_rules}; +use codeint_model::{HazardLine, LanguagePlugin, RepoPath}; + +fn repo_path(path: &str) -> RepoPath { + RepoPath::new(path).unwrap() +} + +fn hazards_for(dialect: SqlDialect, sql: &str) -> Vec { + Sql::with_dialect(dialect) + .lower(&repo_path("query.sql"), sql) + .unwrap_or_else(|err| panic!("failed to lower SQL ({dialect}): {err}")) + .hazard_lines +} + +fn rule_lines(dialect: SqlDialect, sql: &str, rule: &str) -> Vec { + hazards_for(dialect, sql) + .into_iter() + .filter(|h| h.rule == rule) + .map(|h| h.line) + .collect() +} + +fn check_rule(dialect: SqlDialect, rule: &str, hits: &[(&str, &[u32])], misses: &[&str]) { + for &(sql, expected) in hits { + let got = rule_lines(dialect, sql, rule); + assert_eq!(got, expected, "rule {rule} ({dialect}) mismatch on:\n{sql}"); + } + for &sql in misses { + let got = rule_lines(dialect, sql, rule); + assert!( + got.is_empty(), + "rule {rule} ({dialect}) unexpectedly matched at {got:?} on:\n{sql}" + ); + } +} + +#[test] +fn plugin_advertises_all_32_unique_hazard_rules_and_skips_rejected_statements() { + let sql = Sql::new(); + assert!(sql.has_hazard_rules()); + let listed = sql.hazard_rules(); + let exported: Vec = hazard_line_rules().map(str::to_owned).collect(); + assert_eq!(listed, exported); + assert_eq!(SQL_HAZARD_RULES.len(), 32); + let unique: BTreeSet<&str> = SQL_HAZARD_RULES.iter().copied().collect(); + assert_eq!(unique.len(), 32); + for schema_rule in [ + "unknown-column", + "text-compared-to-number", + "filter-on-unindexed-column", + "order-by-unindexed-column", + "join-on-unindexed-column", + ] { + assert!(unique.contains(schema_rule)); + } + + let mixed = "\ +SELECT * FROM users WHERE id = 1; + +NOT VALID SQL SELECT * FROM users DELETE FROM users DROP TABLE users; + +TRUNCATE TABLE logs; +"; + let out = sql + .lower_with_details(&repo_path("mixed.sql"), mixed) + .unwrap(); + assert_eq!(out.rejected_statements.len(), 1); + assert_eq!(out.rejected_statements[0].line, 3); + let pairs: Vec<(u32, &str)> = out + .file_model + .hazard_lines + .iter() + .map(|h| (h.line, h.rule.as_str())) + .collect(); + assert_eq!(pairs, [(1, "select-star"), (5, "truncate")]); +} + +#[test] +fn select_projection_and_set_operation_rules() { + let g = SqlDialect::Generic; + check_rule( + g, + "select-star", + &[ + ("SELECT *\nFROM users\nWHERE id = 1;", &[1]), + ("SELECT\n u.*\nFROM users u\nWHERE u.id = 1;", &[2]), + ( + "SELECT id\nFROM users\nWHERE id IN (\n SELECT * FROM admins\n);", + &[4], + ), + ], + &[ + "SELECT COUNT(*) FROM users WHERE active = true;", + "SELECT id FROM users u WHERE EXISTS (SELECT * FROM orders o WHERE o.id = 1);", + "SELECT id, name FROM users WHERE id = 1;", + "-- SELECT * FROM users\nSELECT 'SELECT * FROM users' FROM dual WHERE 1 < 2;", + ], + ); + check_rule( + g, + "subquery-in-select-list", + &[ + ( + "SELECT\n u.id,\n (\n SELECT COUNT(*) FROM orders o WHERE o.id = 1\n ) AS cnt\nFROM users u\nWHERE u.active = true;", + &[4], + ), + ( + "SELECT u.id,\n COALESCE((SELECT MAX(total) FROM orders), 0)\nFROM users u\nWHERE u.id = 1;", + &[2], + ), + ], + &[ + "SELECT sub.id FROM (SELECT id FROM users WHERE active = true) sub WHERE sub.id > 0;", + "SELECT id FROM users WHERE id IN (SELECT user_id FROM orders WHERE total > 10);", + "-- SELECT (SELECT 1)\nSELECT '(SELECT 1)' FROM users WHERE id = 1;", + ], + ); + check_rule( + g, + "union-without-all", + &[ + ( + "SELECT id FROM users WHERE active = true\nUNION\nSELECT id FROM archived_users WHERE active = true;", + &[2], + ), + ( + "SELECT id FROM a WHERE x = 1\nUNION ALL\nSELECT id FROM b WHERE x = 1\nUNION DISTINCT\nSELECT id FROM c WHERE x = 1;", + &[4], + ), + ], + &[ + "SELECT id FROM a WHERE x = 1 UNION ALL SELECT id FROM b WHERE x = 1;", + "SELECT id FROM a WHERE x = 1 INTERSECT SELECT id FROM b WHERE x = 1;", + "SELECT id FROM a WHERE x = 1 EXCEPT SELECT id FROM b WHERE x = 1;", + "-- SELECT 1 UNION SELECT 2\nSELECT 'UNION' FROM users WHERE id = 1;", + ], + ); + check_rule( + g, + "select-without-filter-or-limit", + &[ + ("SELECT id\nFROM users;", &[1]), + ("SELECT id\nFROM users\nOFFSET 5;", &[1]), + ], + &[ + "SELECT 1;", + "SELECT id FROM users WHERE active = true;", + "SELECT id FROM users LIMIT 10;", + "SELECT id FROM users FETCH FIRST 10 ROWS ONLY;", + "CREATE VIEW active_users AS SELECT id FROM users;", + "CREATE MATERIALIZED VIEW mv_users AS SELECT id FROM users;", + "-- SELECT id FROM users\nSELECT 'SELECT id FROM users';", + ], + ); + check_rule( + g, + "count-without-filter", + &[("SELECT\n COUNT(*)\nFROM users;", &[2])], + &[ + "SELECT COUNT(*) FROM users WHERE active = true;", + "SELECT COUNT(*) FILTER (WHERE active = true) FROM users;", + "SELECT COUNT(id) FROM users;", + "SELECT COUNT(*);", + "-- SELECT COUNT(*) FROM users\nSELECT 'COUNT(*)' FROM users WHERE id = 1;", + ], + ); +} + +#[test] +fn ordering_grouping_distinct_and_offset_rules() { + let g = SqlDialect::Generic; + check_rule( + g, + "large-offset", + &[ + ( + "SELECT id\nFROM users\nWHERE active = true\nLIMIT 20\nOFFSET 1001;", + &[5], + ), + ( + "SELECT id\nFROM users\nWHERE active = true\nOFFSET 5000 ROWS;", + &[4], + ), + ], + &[ + "SELECT id FROM users WHERE active = true LIMIT 20 OFFSET 1000;", + "SELECT id FROM users WHERE active = true LIMIT 20 OFFSET 0;", + "SELECT id FROM users WHERE active = true LIMIT 20 OFFSET $1;", + "-- OFFSET 5000\nSELECT 'OFFSET 5000' FROM users WHERE id = 1;", + ], + ); + assert_eq!( + rule_lines( + SqlDialect::Mysql, + "SELECT id\nFROM users\nWHERE active = 1\nLIMIT 2000, 10;", + "large-offset", + ), + [4] + ); + check_rule( + g, + "distinct-with-order-by", + &[( + "SELECT\n DISTINCT name\nFROM users\nWHERE active = true\nORDER BY name;", + &[2], + )], + &[ + "SELECT DISTINCT name FROM users WHERE active = true;", + "SELECT name FROM users WHERE active = true ORDER BY name;", + "SELECT ALL name FROM users WHERE active = true ORDER BY name;", + "-- SELECT DISTINCT a ORDER BY a\nSELECT 'DISTINCT ORDER BY' FROM users WHERE id = 1;", + ], + ); + check_rule( + g, + "column-position", + &[ + ( + "SELECT dept, COUNT(id)\nFROM emp\nWHERE active = true\nGROUP BY 1;", + &[4], + ), + ( + "SELECT id, name\nFROM users\nWHERE active = true\nORDER BY 2 DESC;", + &[4], + ), + ( + "SELECT id, name\nFROM users\nWHERE active = true\nORDER BY name,\n 1;", + &[5], + ), + ], + &[ + "SELECT dept, COUNT(id) FROM emp WHERE active = true GROUP BY dept;", + "SELECT id, name FROM users WHERE active = true ORDER BY name DESC;", + "SELECT id, a FROM items WHERE active = true ORDER BY a + 1;", + "SELECT id, a FROM items WHERE active = true GROUP BY a + 1;", + "-- ORDER BY 1 GROUP BY 2\nSELECT 'ORDER BY 1' FROM users WHERE id = 1;", + ], + ); + for (dialect, query) in [ + ( + SqlDialect::Postgresql, + "SELECT id\nFROM users\nWHERE active = true\nORDER BY RANDOM()\nLIMIT 5;", + ), + ( + SqlDialect::Postgresql, + "SELECT id\nFROM users\nWHERE active = true\nORDER BY gen_random_uuid()\nLIMIT 5;", + ), + ( + SqlDialect::Mysql, + "SELECT id\nFROM users\nWHERE active = 1\nORDER BY RAND()\nLIMIT 5;", + ), + ( + SqlDialect::Sqlite, + "SELECT id\nFROM users\nWHERE active = 1\nORDER BY random()\nLIMIT 5;", + ), + ( + SqlDialect::Duckdb, + "SELECT id\nFROM users\nWHERE active = true\nORDER BY RANDOM()\nLIMIT 5;", + ), + ( + SqlDialect::Generic, + "SELECT id\nFROM users\nWHERE active = true\nORDER BY NEWID();", + ), + ] { + assert_eq!(rule_lines(dialect, query, "order-by-random"), [4]); + } + check_rule( + g, + "order-by-random", + &[], + &[ + "SELECT RANDOM() FROM users WHERE id = 1;", + "SELECT id FROM users WHERE id = 1 ORDER BY created_at;", + "SELECT id FROM users WHERE id = 1 ORDER BY random_seed;", + "-- ORDER BY RANDOM()\nSELECT 'ORDER BY RANDOM()' FROM users WHERE id = 1;", + ], + ); +} + +#[test] +fn join_and_table_access_rules() { + let g = SqlDialect::Generic; + check_rule( + g, + "tables-without-join-condition", + &[ + ("SELECT a.id, b.id\nFROM users a, orders b;", &[2]), + ( + "SELECT a.id, b.id\nFROM users a\nCROSS JOIN orders b\nWHERE a.id = b.user_id;", + &[3], + ), + ( + "SELECT a.id, b.id\nFROM users a, orders b\nWHERE a.active = true;", + &[2], + ), + ], + &[ + "SELECT a.id, b.id FROM users a, orders b WHERE a.id = b.user_id;", + "SELECT a.id, b.id FROM users a JOIN orders b ON a.id = b.user_id;", + "SELECT a.id, b.id FROM users a JOIN orders b USING (id);", + "SELECT a.id FROM users a NATURAL JOIN orders b;", + "SELECT id FROM users WHERE id = 1;", + "-- CROSS JOIN orders\nSELECT 'CROSS JOIN orders' FROM users WHERE id = 1;", + ], + ); + check_rule( + g, + "distinct-over-join", + &[( + "SELECT\n DISTINCT u.id\nFROM users u\nJOIN orders o ON u.id = o.user_id\nWHERE u.active = true;", + &[2], + )], + &[ + "SELECT DISTINCT id FROM users WHERE active = true;", + "SELECT u.id FROM users u JOIN orders o ON u.id = o.user_id WHERE u.active = true;", + "SELECT ALL u.id FROM users u JOIN orders o ON u.id = o.user_id WHERE u.active = true;", + "-- SELECT DISTINCT a FROM x JOIN y\nSELECT 'DISTINCT JOIN' FROM users WHERE id = 1;", + ], + ); + check_rule( + g, + "table-read-twice", + &[ + ( + "SELECT a.id\nFROM users a\nJOIN users b ON a.manager_id = b.id\nWHERE a.active = true;", + &[3], + ), + ( + "SELECT id\nFROM users\nWHERE manager_id IN (\n SELECT id FROM users WHERE role = 'lead'\n);", + &[4], + ), + ], + &[ + "SELECT a.id FROM public.users a JOIN archive.users b ON a.id = b.id WHERE a.id = 1;", + "WITH active_users AS (SELECT id FROM users WHERE active = true) SELECT a.id FROM active_users a JOIN active_users b ON a.id = b.id WHERE a.id = 1;", + "SELECT a.id FROM users a JOIN orders b ON a.id = b.user_id WHERE a.id = 1;", + "-- FROM users JOIN users\nSELECT 'users users' FROM users WHERE id = 1;", + ], + ); + check_rule( + g, + "join-without-aliases", + &[ + ( + "SELECT users.id, orders.id\nFROM users\nJOIN orders ON users.id = orders.user_id\nWHERE users.active = true;", + &[3], + ), + ( + "SELECT u.id, orders.id\nFROM users u\nJOIN orders ON u.id = orders.user_id\nWHERE u.active = true;", + &[3], + ), + ], + &[ + "SELECT u.id, o.id FROM users u JOIN orders o ON u.id = o.user_id WHERE u.active = true;", + "SELECT u.id, o.id FROM users u, orders o WHERE u.id = o.user_id;", + "SELECT id FROM users WHERE active = true;", + "-- FROM users JOIN orders\nSELECT 'JOIN orders' FROM users WHERE id = 1;", + ], + ); +} + +#[test] +fn subquery_correlation_and_nesting_rules() { + let g = SqlDialect::Generic; + check_rule( + g, + "subquery-refers-to-outer-table", + &[ + ( + "SELECT u.id\nFROM users u\nWHERE EXISTS (\n SELECT 1\n FROM orders o\n WHERE o.user_id = u.id\n);", + &[4], + ), + ( + "SELECT id\nFROM users\nWHERE EXISTS (\n SELECT 1\n FROM orders\n WHERE orders.user_id = users.id\n);", + &[4], + ), + ( + "UPDATE users u\nSET total = (\n SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id\n)\nWHERE u.id = 1;", + &[3], + ), + ], + &[ + "SELECT u.id FROM users u WHERE u.id IN (SELECT o.user_id FROM orders o WHERE o.total > 10);", + "SELECT u.id FROM users u WHERE EXISTS (SELECT 1 FROM orders u WHERE u.total > 10);", + "-- WHERE o.user_id = u.id\nSELECT 'u.id' FROM users u WHERE u.id = 1;", + ], + ); + check_rule( + g, + "deep-subquery-nesting", + &[ + ( + "SELECT id\nFROM a\nWHERE x IN (\n SELECT id FROM b WHERE y IN (\n SELECT id FROM c WHERE z IN (\n SELECT id FROM d WHERE k = 1\n )\n )\n);", + &[6], + ), + ( + "SELECT t3.id\nFROM (\n SELECT t2.id FROM (\n SELECT t1.id FROM (\n SELECT id FROM base WHERE id = 1\n ) t1\n ) t2\n) t3\nWHERE t3.id = 1;", + &[5], + ), + ], + &[ + "SELECT id FROM a WHERE x IN (SELECT id FROM b WHERE y IN (SELECT id FROM c WHERE k = 1));", + "SELECT id FROM a WHERE x IN (SELECT id FROM b WHERE k = 1) AND y IN (SELECT id FROM c WHERE k = 1) AND z IN (SELECT id FROM d WHERE k = 1);", + "-- (SELECT (SELECT (SELECT 1)))\nSELECT '(SELECT (SELECT (SELECT 1)))' FROM a WHERE id = 1;", + ], + ); +} + +#[test] +fn predicate_and_filter_rules() { + let g = SqlDialect::Generic; + check_rule( + g, + "leading-wildcard-like", + &[ + ("SELECT id\nFROM users\nWHERE name LIKE '%smith';", &[3]), + ("SELECT id\nFROM users\nWHERE code LIKE '_abc';", &[3]), + ( + "SELECT id\nFROM users\nWHERE email\n ILIKE '%@example.com';", + &[4], + ), + ("SELECT id\nFROM users\nWHERE name NOT LIKE '%test%';", &[3]), + ], + &[ + "SELECT id FROM users WHERE name LIKE 'smith%';", + "SELECT id FROM users WHERE code LIKE 'abc_';", + "SELECT id FROM users WHERE name LIKE $1;", + "SELECT id FROM users WHERE name LIKE ?;", + "SELECT id FROM users WHERE name LIKE pattern_col;", + "-- WHERE name LIKE '%foo'\nSELECT 'LIKE ''%foo''' FROM users WHERE id = 1;", + ], + ); + check_rule( + g, + "function-on-filter-column", + &[ + ( + "SELECT id\nFROM users\nWHERE LOWER(email) = 'a@example.com';", + &[3], + ), + ( + "SELECT a.id\nFROM users a\nJOIN orders b\n ON DATE(a.created_at) = b.order_date\nWHERE a.id = 1;", + &[4], + ), + ( + "SELECT dept\nFROM emp\nGROUP BY dept\nHAVING LOWER(dept) = 'sales';", + &[4], + ), + ( + "SELECT id\nFROM users\nWHERE EXTRACT(YEAR FROM created_at) = 2026;", + &[3], + ), + ("SELECT id\nFROM users\nWHERE TRIM(name) = 'alice';", &[3]), + ], + &[ + "SELECT LOWER(email) FROM users WHERE id = 1;", + "SELECT id FROM users WHERE status = LOWER('ACTIVE');", + "SELECT id FROM users WHERE created_at > NOW();", + "SELECT dept FROM emp GROUP BY dept HAVING SUM(salary) > 100;", + "-- WHERE LOWER(email) = 'x'\nSELECT 'LOWER(email)' FROM users WHERE id = 1;", + ], + ); + check_rule( + g, + "not-in-subquery", + &[( + "SELECT id\nFROM users\nWHERE id\n NOT IN (SELECT user_id FROM banned WHERE active = true);", + &[4], + )], + &[ + "SELECT id FROM users WHERE id NOT IN (1, 2, 3);", + "SELECT id FROM users WHERE id IN (SELECT user_id FROM admins WHERE active = true);", + "SELECT u.id FROM users u WHERE NOT EXISTS (SELECT 1 FROM banned b WHERE b.id = 1);", + "-- NOT IN (SELECT id FROM t)\nSELECT 'NOT IN (SELECT 1)' FROM users WHERE id = 1;", + ], + ); + check_rule( + g, + "always-true-condition", + &[ + ("SELECT id\nFROM users\nWHERE 1 = 1;", &[3]), + ( + "SELECT id\nFROM users\nWHERE name = 'alice'\n OR 1 = 1;", + &[4], + ), + ( + "SELECT id\nFROM users\nWHERE name = 'alice'\n OR 'a' = 'a';", + &[4], + ), + ("SELECT id\nFROM users\nWHERE TRUE;", &[3]), + ( + "SELECT id\nFROM users\nWHERE active = false\n OR TRUE;", + &[4], + ), + ("SELECT id\nFROM users\nWHERE NOT FALSE;", &[3]), + ], + &[ + "SELECT id FROM users WHERE 1 = 2;", + "SELECT id FROM users WHERE 'a' = 'b';", + "SELECT id FROM users WHERE a = a;", + "SELECT id FROM users WHERE active = TRUE;", + "SELECT id FROM users WHERE NULL = NULL;", + "SELECT id FROM users WHERE $1 = $1;", + "SELECT TRUE FROM users WHERE id = 1;", + "-- WHERE 1 = 1\nSELECT 'OR 1 = 1' FROM users WHERE id = 1;", + ], + ); + + let items_101: String = (1..=101) + .map(|n| n.to_string()) + .collect::>() + .join(", "); + let items_100: String = (1..=100) + .map(|n| n.to_string()) + .collect::>() + .join(", "); + let hit_in = format!("SELECT id\nFROM users\nWHERE id IN ({items_101});"); + let miss_100 = format!("SELECT id\nFROM users\nWHERE id IN ({items_100});"); + let comment_in = + format!("-- WHERE id IN ({items_101})\nSELECT 'IN ({items_101})' FROM users WHERE id = 1;"); + check_rule( + g, + "long-in-list", + &[(&hit_in, &[3])], + &[ + &miss_100, + "SELECT id FROM users WHERE id IN (SELECT user_id FROM orders WHERE total > 0);", + &comment_in, + ], + ); +} + +#[test] +fn destructive_dml_ddl_dcl_and_dynamic_sql_rules() { + let g = SqlDialect::Generic; + check_rule( + g, + "update-without-filter", + &[("\nUPDATE users\nSET active = false;", &[2])], + &[ + "UPDATE users SET active = false WHERE id = 1;", + "-- UPDATE users SET active = false\nSELECT 'UPDATE users SET x = 1' FROM users WHERE id = 1;", + ], + ); + check_rule( + g, + "delete-without-filter", + &[("\nDELETE FROM users;", &[2])], + &[ + "DELETE FROM users WHERE id = 1;", + "-- DELETE FROM users\nSELECT 'DELETE FROM users' FROM users WHERE id = 1;", + ], + ); + check_rule( + g, + "truncate", + &[("\nTRUNCATE TABLE audit_log;", &[2])], + &[ + "SELECT TRUNCATE(3.14, 1) FROM dual WHERE id = 1;", + "-- TRUNCATE TABLE audit_log\nSELECT 'TRUNCATE TABLE audit_log' FROM users WHERE id = 1;", + ], + ); + check_rule( + g, + "drop", + &[ + ("DROP TABLE legacy_users;", &[1]), + ("\nDROP VIEW IF EXISTS old_report;", &[2]), + ("DROP INDEX IF EXISTS idx_old;", &[1]), + ("DROP FUNCTION IF EXISTS old_fn;", &[1]), + ("DROP TRIGGER IF EXISTS trg_old ON users;", &[1]), + ], + &[ + "ALTER TABLE users DROP COLUMN legacy_col;", + "ALTER TABLE users DROP CONSTRAINT fk_org;", + "-- DROP TABLE users\nSELECT 'DROP TABLE users' FROM users WHERE id = 1;", + ], + ); + check_rule( + g, + "grant-or-revoke", + &[ + ("GRANT SELECT ON users TO analyst;", &[1]), + ("\nREVOKE INSERT ON users FROM analyst;", &[2]), + ], + &[ + "SELECT id FROM grants WHERE id = 1;", + "-- GRANT ALL ON users TO public\nSELECT 'REVOKE ALL' FROM users WHERE id = 1;", + ], + ); + check_rule( + g, + "sql-built-at-run-time", + &[ + ("EXECUTE IMMEDIATE 'SELECT id FROM users';", &[1]), + ("\nEXECUTE ('SELECT id FROM ' || tbl_name);", &[2]), + ("EXECUTE ('SELECT 1');", &[1]), + ("EXEC sp_executesql 'SELECT 1';", &[1]), + ], + &[ + "EXECUTE my_stmt(1);", + "EXECUTE my_stmt;", + "PREPARE my_stmt AS SELECT id FROM users WHERE id = $1;", + "-- EXECUTE IMMEDIATE 'SELECT 1'\nSELECT 'EXECUTE IMMEDIATE' FROM users WHERE id = 1;", + ], + ); + assert_eq!( + rule_lines( + SqlDialect::Postgresql, + "EXECUTE format('SELECT * FROM %I', tbl);", + "sql-built-at-run-time", + ), + [1] + ); +} + +#[test] +fn plain_text_secret_rules_and_no_secret_leakage() { + let sentinel = "s3cr3t_t0k3n_never_leak_98765"; + let pg_role = format!("CREATE ROLE app_user\nWITH LOGIN PASSWORD '{sentinel}';"); + let pg_alter = format!("ALTER USER app_user\nWITH PASSWORD '{sentinel}';"); + let pg_alter_role = format!("ALTER ROLE app_user\nWITH PASSWORD '{sentinel}';"); + let duck_secret = format!("CREATE SECRET my_s3 (\n TYPE S3,\n SECRET '{sentinel}'\n);"); + let insert_pw = format!("INSERT INTO users (name, password)\nVALUES ('alice', '{sentinel}');"); + let insert_api = + format!("INSERT INTO integrations (service, api_key)\nVALUES ('stripe', '{sentinel}');"); + let update_token = format!("UPDATE sessions\nSET access_key = '{sentinel}'\nWHERE id = 1;"); + let update_priv = format!("UPDATE certs\nSET private_key = '{sentinel}'\nWHERE id = 1;"); + let update_passwd = format!( + "UPDATE accounts\nSET user_passwd = '{sentinel}',\n pwd_backup = '{sentinel}',\n apikey = '{sentinel}',\n auth_token = '{sentinel}'\nWHERE id = 1;" + ); + + check_rule( + SqlDialect::Postgresql, + "plain-text-secret", + &[(&pg_role, &[2]), (&pg_alter, &[2]), (&pg_alter_role, &[2])], + &[ + "CREATE ROLE app_user WITH PASSWORD NULL;", + "ALTER USER app_user WITH PASSWORD NULL;", + "INSERT INTO users (name, password) VALUES ('alice', $1);", + "INSERT INTO users (name, password) VALUES ('alice', ?);", + "INSERT INTO users (name, password) VALUES ('alice', :pwd);", + "INSERT INTO users (name, password) VALUES ('alice', crypt($1, gen_salt('bf')));", + "INSERT INTO users (name, password) VALUES ('alice', NULL);", + "UPDATE users SET password = $1 WHERE id = 1;", + "UPDATE users SET api_key = sha256(seed) WHERE id = 1;", + "UPDATE users SET display_name = 'alice' WHERE id = 1;", + "-- UPDATE users SET password = 'abc'\nSELECT 'PASSWORD ''abc''' FROM users WHERE id = 1;", + ], + ); + assert_eq!( + rule_lines(SqlDialect::Duckdb, &duck_secret, "plain-text-secret"), + [3] + ); + check_rule( + SqlDialect::Generic, + "plain-text-secret", + &[ + (&insert_pw, &[2]), + (&insert_api, &[2]), + (&update_token, &[2]), + (&update_priv, &[2]), + (&update_passwd, &[2, 3, 4, 5]), + ], + &[], + ); + + for sql in [&pg_role, &insert_pw, &update_token] { + let lines = hazards_for(SqlDialect::Postgresql, sql); + assert!(!lines.is_empty()); + let debug_repr = format!("{lines:?}"); + assert!(!debug_repr.contains(sentinel)); + } +} From bc7f6f8d1706f87276c5ddca520c0401fd77730c Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Tue, 24 Nov 2026 21:36:42 +0800 Subject: [PATCH 06/12] docs(docs): document SQL plugin, Dialects, Hazards Metric, and SQL Schema Add user guides for the built-in SQL Language plugin and the Hazards Metric, document all SQL and Hazards configuration keys, report fields, and all 32 Hazard line rules in docs/reference.md, and update README, llms.txt, GLOSSARY.md, .rules, and guide pages. Closes #314 Closes #329 Closes #371 Closes #382 --- .rules | 4 +- GLOSSARY.md | 6 +- README.md | 7 +- docs/guide/README.md | 18 ++- docs/guide/configuration.md | 23 ++- docs/guide/hazards.md | 85 +++++++++++ docs/guide/languages.md | 11 +- docs/guide/mcp.md | 6 +- docs/guide/philosophy-and-architecture.md | 8 +- docs/guide/sql.md | 132 ++++++++++++++++ docs/plugins.md | 10 +- docs/reference.md | 177 ++++++++++++++++++++-- llms.txt | 12 +- 13 files changed, 450 insertions(+), 49 deletions(-) create mode 100644 docs/guide/hazards.md create mode 100644 docs/guide/sql.md diff --git a/.rules b/.rules index 6eea35b1..f1c02f5b 100644 --- a/.rules +++ b/.rules @@ -1,7 +1,7 @@ # Agent guidance -codeint is a command-line tool that measures the Software entropy of a codebase, in any language that has a Language plugin, so that developers who work with coding agents see it grow before it compounds. -Built-in Language plugins cover TypeScript/JavaScript/Vue/Svelte, Rust, PHP, Dart, Python, and Go. +codeint is a command-line tool that measures the Software entropy of a codebase, and reports Hazards next to Software entropy, in any language that has a Language plugin, so that developers who work with coding agents see it grow before it compounds. +Built-in Language plugins cover TypeScript/JavaScript/Vue/Svelte, Rust, PHP, Dart, Python, Go, and SQL. Test gap measures untested Production Function mass from user-named LCOV or Cobertura XML Coverage reports; codeint never runs tests and never guesses report paths. Kit: avidianity/factory v0.4.0, bootstrapped 2026-11-21. diff --git a/GLOSSARY.md b/GLOSSARY.md index b62ec214..bf60b09c 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -1,8 +1,8 @@ # codeint -codeint measures the Software entropy of a codebase, in any language that has a Language plugin: Erosion, Cognitive complexity, Test gap, Duplication, Verbosity, Import cycles, Import boundaries, Orphan files, and Dependency hygiene. +codeint measures the Software entropy of a codebase (Erosion, Cognitive complexity, Test gap, Duplication, Verbosity, Import cycles, Import boundaries, Orphan files, and Dependency hygiene) and reports Hazards next to Software entropy, in any language that has a Language plugin. It is for developers whose code is increasingly written by coding agents, so they see Software entropy grow before it compounds. -Built-in Language plugins cover TypeScript/JavaScript/Vue/Svelte, Rust, PHP, Dart, Python, and Go. +Built-in Language plugins cover TypeScript/JavaScript/Vue/Svelte, Rust, PHP, Dart, Python, Go, and SQL. ## Language @@ -92,7 +92,7 @@ A package declared by a repository workspace or by a module manifest such as `go _Avoid_: subpackage, member package, workspace member **Finding**: -One located piece of evidence behind a Metric value, such as an eroded function, an untested function, a Clone group, a Flagged line, or an Import cycle. +One located piece of evidence behind a Metric value, such as an eroded function, an untested function, a Clone group, a Flagged line, a Hazard line, or an Import cycle. _Avoid_: issue, violation, warning, hotspot **Reference range**: diff --git a/README.md b/README.md index 9c2d96ff..2fdf6382 100644 --- a/README.md +++ b/README.md @@ -30,8 +30,8 @@ Coding agents write locally valid code very quickly. Each pull request can pass tests and linters while quietly adding copied blocks, redundant branches, deeper functions, unused dependencies, and tangled imports. Over dozens of changes, that structural drag compounds until both humans and agents slow down. -codeint measures **Software entropy** directly from the shape of your source code so you see it grow before it compounds. -It ships with six built-in Language plugins covering TypeScript/JavaScript (including React `.jsx`/`.tsx`, Vue, and Svelte `