Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 22 additions & 22 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 6 additions & 6 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,12 @@ sha2 = "0.10"
similar = "2"
sqlclean = { path = "crates/sqlclean" }
# SQLQuack's formatter and lint engine, and the tokens and trees they read, which replace Polyglot.
sqlquack-fingerprint = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "ae2bef7a2299fa202212c721a7c173a9c32fb9bb", features = ["bigquery", "databricks", "duckdb", "postgres", "snowflake", "sqlite", "sqlserver"] }
sqlquack-format = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "ae2bef7a2299fa202212c721a7c173a9c32fb9bb", features = ["bigquery", "databricks", "duckdb", "postgres", "snowflake", "sqlserver"] }
sqlquack-lint = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "ae2bef7a2299fa202212c721a7c173a9c32fb9bb", features = ["bigquery", "databricks", "duckdb", "postgres", "snowflake", "sqlite"] }
sqlquack-parse = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "ae2bef7a2299fa202212c721a7c173a9c32fb9bb" }
sqlquack-syntax = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "ae2bef7a2299fa202212c721a7c173a9c32fb9bb" }
sqlquack-syntax-sqlserver = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "ae2bef7a2299fa202212c721a7c173a9c32fb9bb" }
sqlquack-fingerprint = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "b938ec518b6ab5491090c55832f7d5a4059059bf", features = ["bigquery", "databricks", "duckdb", "postgres", "snowflake", "sqlite", "sqlserver"] }
sqlquack-format = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "b938ec518b6ab5491090c55832f7d5a4059059bf", features = ["bigquery", "databricks", "duckdb", "postgres", "snowflake", "sqlserver"] }
sqlquack-lint = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "b938ec518b6ab5491090c55832f7d5a4059059bf", features = ["bigquery", "databricks", "duckdb", "postgres", "snowflake", "sqlite"] }
sqlquack-parse = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "b938ec518b6ab5491090c55832f7d5a4059059bf" }
sqlquack-syntax = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "b938ec518b6ab5491090c55832f7d5a4059059bf" }
sqlquack-syntax-sqlserver = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "b938ec518b6ab5491090c55832f7d5a4059059bf" }

[workspace.lints.rust]
unsafe_code = "forbid"
Expand Down
5 changes: 3 additions & 2 deletions crates/sqlclean-cli/skill/references/docs/cli/facts.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ so use it to see what a Rule will read before writing one.
## Usage

```bash
sqlclean facts [--dialect <DIALECT>] < query.sql
sqlclean facts [--dialect <DIALECT>] [--max-function-call-depth <N>] < query.sql
```

```bash
Expand All @@ -26,6 +26,7 @@ echo "SELECT o.order_id, COUNT(*) AS items FROM orders AS o JOIN order_items AS
| Flag | Description |
|------|-------------|
| `--dialect <DIALECT>` | The dialect to parse with (default: `generic`); see [Dialects](../configuration.md#dialects) |
| `--max-function-call-depth <N>` | The deepest function-call nesting to parse, from `1` to `512` (default: `256`); pass your `max_function_call_depth` setting so `facts` reads what `check` reads |

`facts` reads no configuration file and no paths.

Expand Down Expand Up @@ -75,4 +76,4 @@ facts with `line`, `column` and `text` added to every node. See
| Code | Meaning |
|------|---------|
| `0` | The facts were printed |
| `2` | The SQL does not parse under the dialect, or the dialect is unknown |
| `2` | The SQL does not parse under the dialect, nests function calls deeper than the limit, or the dialect is unknown |
2 changes: 2 additions & 0 deletions crates/sqlclean-cli/skill/references/docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ applies.
dialect = "duckdb" # default "generic"
include = ["**/*.sql"]
exclude = ["vendor/**"]
max_function_call_depth = 256 # nested function calls a file may hold

[[dialects]] # a different dialect for some paths
paths = ["warehouse/**"]
Expand Down Expand Up @@ -71,6 +72,7 @@ directory is the root.
| `include` | `["**/*.sql"]` | Glob patterns of the files to read |
| `exclude` | `[]` | Glob patterns of files never to read |
| `[[dialects]]` | none | `paths` and `dialect`: a different dialect for matching files |
| `max_function_call_depth` | `256` | The deepest function-call nesting SQLClean parses, from `1` to `512`; a file nested deeper is a `SQLCLEAN999` finding and is not formatted |
| `[format] line_width` | `100` | The line width the formatter fills; see [Line width](formatting.md#line-width) |
| `[format] indent` | `4` | Spaces per indent step, from `1` to `8`; see [Indent](formatting.md#indent) |
| `[rules] select` | Rules enabled by default | Rule codes or prefixes to run |
Expand Down
4 changes: 4 additions & 0 deletions crates/sqlclean-cli/skill/references/docs/embedding.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ the dialect. Offsets in requests, findings, edits and facts count Unicode charac
| `ignored_rules` | `[]` | Rule codes or prefixes to skip |
| `max_literal_length` | `100` | The `SQLCLEAN044` limit |
| `max_ranking_order_by` | `5` | The `SQLCLEAN043` limit |
| `max_function_call_depth` | `256` | Function calls nested deeper than this are a parse error that names this setting; at most `512` |
| `config_file` | `sqlclean.toml` | The configuration file name that remediation text refers to |
| `long_literal_guidance` | SQLClean's advice | The advice `SQLCLEAN044` gives before its `max_literal_length` setting, so a host can point at its own way to share a value |
| `externally_referenced_ctes` | `[]` | CTE names that something outside the SQL reads, so `SQLCLEAN005` does not report them |
Expand Down Expand Up @@ -150,6 +151,9 @@ println!("{}", format_json(request)?);
`indent` sets the spaces per indent step. Without it the engine indents two spaces, its layout
before the `sqlclean` command chose four; pass `"indent": 4` to match `sqlclean format`.

`max_function_call_depth` bounds nested function calls as it does in a lint request: `256` by
default, at most `512`.

When the formatter cannot format the SQL, `formatted` is `false`, `sql` is the input unchanged,
and `reason` says why.

Expand Down
3 changes: 2 additions & 1 deletion crates/sqlclean-cli/src/checking/_helpers/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use crate::positions::models::Edit;
pub(crate) fn builtin_findings(
file: &SourceFile,
codes: &BTreeSet<String>,
thresholds: Thresholds,
(thresholds, max_function_call_depth): (Thresholds, usize),
) -> Vec<Finding> {
let request = LintRequest {
version: LINT_API_VERSION,
Expand All @@ -30,6 +30,7 @@ pub(crate) fn builtin_findings(
enabled_rules: Some(codes.iter().cloned().collect()),
max_literal_length: Some(thresholds.max_literal_length),
max_ranking_order_by: Some(thresholds.max_ranking_order_by),
max_function_call_depth: Some(max_function_call_depth),
config_file: Some(CONFIG_FILE_NAME.to_owned()),
..LintRequest::default()
};
Expand Down
13 changes: 8 additions & 5 deletions crates/sqlclean-cli/src/checking/_helpers/custom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,13 @@ pub(crate) fn custom_findings(
if misses.is_empty() {
return Ok(findings);
}
let depth: usize = evaluation.config.max_function_call_depth;
let mut host_files: Vec<HostFile> = pending
.into_par_iter()
.map(|(file, missing)| host_file(file, missing))
.map(|(file, missing)| host_file(file, missing, depth))
.collect::<Result<_, _>>()?;
if !missing_repository.is_empty() {
host_files = with_every_file(files, host_files)?;
host_files = with_every_file(files, host_files, depth)?;
}
let results: Vec<HostResult> =
evaluate_on_hosts(evaluation, options, host_files, missing_repository)?;
Expand Down Expand Up @@ -188,8 +189,9 @@ fn file_key(
])
}

fn host_file(file: &SourceFile, rules: Vec<String>) -> Result<HostFile, String> {
let facts = file_facts(&file.text, &file.dialect)?;
/// The file as a Rule host reads it, its facts parsed within the configured call-depth limit.
fn host_file(file: &SourceFile, rules: Vec<String>, depth: usize) -> Result<HostFile, String> {
let facts = file_facts(&file.text, &file.dialect, Some(depth))?;
if let Some(reason) = facts.unavailable {
return Err(reason);
}
Expand All @@ -206,10 +208,11 @@ fn host_file(file: &SourceFile, rules: Vec<String>) -> Result<HostFile, String>
fn with_every_file(
files: &[&SourceFile],
mut host_files: Vec<HostFile>,
depth: usize,
) -> Result<Vec<HostFile>, String> {
for file in files {
if !host_files.iter().any(|host| host.path == file.path) {
host_files.push(host_file(file, Vec::new())?);
host_files.push(host_file(file, Vec::new(), depth)?);
}
}
host_files.sort_by(|left, right| left.path.cmp(&right.path));
Expand Down
7 changes: 5 additions & 2 deletions crates/sqlclean-cli/src/checking/_helpers/orchestration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,9 @@ fn run_builtins(run: &BuiltinRun<'_>, mut cache: ResultCache) -> (Vec<Finding>,
.collect();
let selection: String = codes.iter().cloned().collect::<Vec<String>>().join(",");
let thresholds = run.config.rules.thresholds;
let depth: usize = run.config.max_function_call_depth;
let limits: String = format!(
"{}:{}",
"{}:{}:{depth}",
thresholds.max_literal_length, thresholds.max_ranking_order_by
);
let keys: Vec<String> = run
Expand All @@ -160,7 +161,9 @@ fn run_builtins(run: &BuiltinRun<'_>, mut cache: ResultCache) -> (Vec<Finding>,
.files
.par_iter()
.zip(cached)
.map(|(file, cached)| cached.unwrap_or_else(|| builtin_findings(file, &codes, thresholds)))
.map(|(file, cached)| {
cached.unwrap_or_else(|| builtin_findings(file, &codes, (thresholds, depth)))
})
.collect();
for ((file, key), found) in run.files.iter().zip(&keys).zip(&computed) {
cache.put(key, Some(&file.path), found);
Expand Down
12 changes: 11 additions & 1 deletion crates/sqlclean-cli/src/command/_helpers/facts_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,26 @@
use std::io::{Read, Write};

use sqlclean::sql_facts::main::file_facts::file_facts;
use sqlclean::sql_lint::constants::MAX_CALL_DEPTH_CEILING;

use crate::command::constants::EXIT_SUCCESS;
use crate::command::models::FactsArgs;

pub(crate) fn run(arguments: &FactsArgs) -> Result<u8, String> {
if !(1..=MAX_CALL_DEPTH_CEILING).contains(&arguments.max_function_call_depth) {
return Err(format!(
"--max-function-call-depth must be between 1 and {MAX_CALL_DEPTH_CEILING}"
));
}
let mut sql = String::new();
std::io::stdin()
.read_to_string(&mut sql)
.map_err(|error| error.to_string())?;
let facts = file_facts(&sql, &arguments.dialect)?;
let facts = file_facts(
&sql,
&arguments.dialect,
Some(arguments.max_function_call_depth),
)?;
let json: String = serde_json::to_string(&facts).map_err(|error| error.to_string())?;
let _ = writeln!(std::io::stdout(), "{json}");
Ok(EXIT_SUCCESS)
Expand Down
12 changes: 11 additions & 1 deletion crates/sqlclean-cli/src/command/_helpers/format_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,17 @@ pub(crate) fn run(config: &Config, arguments: &FormatArgs) -> Result<u8, String>
let (mut changed, mut refused, mut unavailable): (usize, usize, usize) = (0, 0, 0);
let results: Vec<Result<Formatted, String>> = files
.par_iter()
.map(|file| format_source(&file.text, &file.dialect, config.line_width, config.indent))
.map(|file| {
format_source(
&file.text,
&file.dialect,
(
config.line_width,
config.indent,
config.max_function_call_depth,
),
)
})
.collect();
for (file, result) in files.iter().zip(results) {
let formatted: String = match result {
Expand Down
4 changes: 4 additions & 0 deletions crates/sqlclean-cli/src/command/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use std::path::PathBuf;

use clap::{Args, Parser, Subcommand};
use sqlclean::sql_lint::constants::MAX_FUNCTION_CALL_DEPTH;

use crate::reporting::models::OutputFormat;

Expand Down Expand Up @@ -94,6 +95,9 @@ pub struct RulesArgs {
pub struct FactsArgs {
#[arg(long, default_value = "generic")]
pub dialect: String,
/// Most nested function calls the parser follows, from 1 to 512.
#[arg(long, default_value_t = MAX_FUNCTION_CALL_DEPTH)]
pub max_function_call_depth: usize,
}

#[derive(Debug, Args)]
Expand Down
1 change: 1 addition & 0 deletions crates/sqlclean-cli/src/config/_helpers/file_schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use crate::config::models::{DialectOverride, RuleException, RuleIgnore, Threshol
pub(crate) struct ConfigFile {
pub(crate) dialect: Option<String>,
pub(crate) include: Option<Vec<String>>,
pub(crate) max_function_call_depth: Option<usize>,
#[serde(default)]
pub(crate) exclude: Vec<String>,
#[serde(default)]
Expand Down
5 changes: 5 additions & 0 deletions crates/sqlclean-cli/src/config/_helpers/loading.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
use std::fs;
use std::path::{Path, PathBuf};

use sqlclean::sql_lint::constants::MAX_FUNCTION_CALL_DEPTH;

use crate::config::_helpers::file_schema::ConfigFile;
use crate::config::_helpers::validation::validate;
use crate::config::constants::{
Expand Down Expand Up @@ -52,6 +54,9 @@ fn effective_config(root: PathBuf, file: ConfigFile) -> Config {
dialects: file.dialects,
line_width: file.format.line_width.unwrap_or(DEFAULT_LINE_WIDTH),
indent: file.format.indent.unwrap_or(DEFAULT_INDENT),
max_function_call_depth: file
.max_function_call_depth
.unwrap_or(MAX_FUNCTION_CALL_DEPTH),
rules: RulesConfig {
select: file.rules.select,
ignore: file.rules.ignore,
Expand Down
6 changes: 6 additions & 0 deletions crates/sqlclean-cli/src/config/_helpers/validation.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Checks that need more than the schema: positive limits, valid globs, dialects and reasons.

use globset::Glob;
use sqlclean::sql_lint::constants::MAX_CALL_DEPTH_CEILING;
use sqlclean::sql_lint::main::validate_dialect::validate_dialect;

use crate::config::constants::MAX_INDENT;
Expand All @@ -22,6 +23,11 @@ pub(crate) fn validate(config: &Config) -> Result<(), String> {
"[format] indent must be between 1 and {MAX_INDENT}"
));
}
if !(1..=MAX_CALL_DEPTH_CEILING).contains(&config.max_function_call_depth) {
return Err(format!(
"max_function_call_depth must be between 1 and {MAX_CALL_DEPTH_CEILING}"
));
}
let thresholds = config.rules.thresholds;
if thresholds.max_literal_length == 0 || thresholds.max_ranking_order_by == 0 {
return Err(
Expand Down
2 changes: 2 additions & 0 deletions crates/sqlclean-cli/src/config/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ pub struct Config {
pub line_width: usize,
/// Spaces per indent step in formatted SQL.
pub indent: usize,
/// Function calls nested deeper than this make a file unparseable.
pub max_function_call_depth: usize,
pub rules: RulesConfig,
}

Expand Down
Loading
Loading